明显的不同:承诺拒绝在不同地方得到处理
return somePromise
会将somePromise传递到呼叫站点,并将await
somePromise传递到呼叫站点(如果有)。因此,如果somePromise被拒绝,它将不会由本地catch块处理,而是由呼叫站点的catch块处理。
async function foo () {
try {
return Promise.reject();
} catch (e) {
console.log('IN');
}
}
(async function main () {
try {
let a = await foo();
} catch (e) {
console.log('OUT');
}
})();
// 'OUT'
return await somePromise
首先要等待一些承诺在当地定居。因此,值或Exception首先将在本地处理。=>如果somePromise
拒绝,将执行本地catch块。
async function foo () {
try {
return await Promise.reject();
} catch (e) {
console.log('IN');
}
}
(async function main () {
try {
let a = await foo();
} catch (e) {
console.log('OUT');
}
})();
// 'IN'
原因:return await Promise
本地和外部return Promise
等待,仅外部等待
详细步骤:
回报承诺
async function delay1Second() {
return delay(1000);
}
- 打电话
delay1Second()
;
const result = await delay1Second();
- 在内部
delay1Second()
,函数delay(1000)
立即使用[[PromiseStatus]]: 'pending
。叫它delayPromise
。
async function delay1Second() {
return delayPromise;
// delayPromise.[[PromiseStatus]]: 'pending'
// delayPromise.[[PromiseValue]]: undefined
}
- 异步函数会将其返回值包装在
Promise.resolve()
(Source)中。因为delay1Second
是异步函数,所以我们有:
const result = await Promise.resolve(delayPromise);
// delayPromise.[[PromiseStatus]]: 'pending'
// delayPromise.[[PromiseValue]]: undefined
Promise.resolve(delayPromise)
delayPromise
不做任何事情就返回,因为输入已经是一个承诺(请参见MDN Promise.resolve):
const result = await delayPromise;
// delayPromise.[[PromiseStatus]]: 'pending'
// delayPromise.[[PromiseValue]]: undefined
await
等待,直到delayPromise
结算。
- 如果
delayPromise
满足PromiseValue = 1:
const result = 1;
// jump to catch block if there is any
返回等待承诺
async function delay1Second() {
return await delay(1000);
}
- 打电话
delay1Second()
;
const result = await delay1Second();
- 在内部
delay1Second()
,函数delay(1000)
立即使用[[PromiseStatus]]: 'pending
。叫它delayPromise
。
async function delay1Second() {
return await delayPromise;
// delayPromise.[[PromiseStatus]]: 'pending'
// delayPromise.[[PromiseValue]]: undefined
}
- 当地的等待将等到
delayPromise
解决。
- 情况1:
delayPromise
以PromiseValue = 1满足:
async function delay1Second() {
return 1;
}
const result = await Promise.resolve(1); // let's call it "newPromise"
const result = await newPromise;
// newPromise.[[PromiseStatus]]: 'resolved'
// newPromise.[[PromiseValue]]: 1
const result = 1;
// jump to catch block inside `delay1Second` if there is any
// let's say a value -1 is returned in the end
const result = await Promise.resolve(-1); // call it newPromise
const result = await newPromise;
// newPromise.[[PromiseStatus]]: 'resolved'
// newPromise.[[PromiseValue]]: -1
const result = -1;
词汇表:
- 解决:
Promise.[[PromiseStatus]]
从更改pending
为resolved
或rejected