ความแตกต่างที่เห็นได้ชัดเจน: การปฏิเสธสัญญาจะได้รับการจัดการในสถานที่ต่างๆ
return somePromiseจะส่งผ่านsomePromiseไปยังไซต์การโทรและawait somePromise ที่จะชำระที่ไซต์การโทร (ถ้ามี) ดังนั้นหาก somePromise ถูกปฏิเสธจะไม่ได้รับการจัดการโดย catch block ในพื้นที่ แต่เป็นบล็อก 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');
}
})();
return await somePromiseก่อนอื่นจะรอบางส่วนสัญญาว่าจะตั้งถิ่นฐานในพื้นที่ ดังนั้นค่าหรือ Exception จะถูกจัดการในเครื่องก่อน => Local catch block จะถูกดำเนินการหากsomePromiseถูกปฏิเสธ
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');
}
})();
เหตุผล: 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;
}
- ฟังก์ชัน Async จะรวมค่าส่งคืนไว้ภายใน
Promise.resolve()( Source ) เนื่องจากdelay1Secondเป็นฟังก์ชัน async เราจึงมี:
const result = await Promise.resolve(delayPromise);
Promise.resolve(delayPromise)ส่งคืนdelayPromiseโดยไม่ต้องทำอะไรเลยเพราะอินพุตเป็นสัญญาอยู่แล้ว (ดูMDN Promise.resolve ):
const result = await delayPromise;
awaitรอจนกว่าdelayPromiseจะมีการตัดสิน
- IF
delayPromiseเป็นจริงด้วย PromiseValue = 1:
const result = 1;
- ELSE
delayPromiseถูกปฏิเสธ:
กลับมารอสัญญา
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ได้รับการตัดสิน
- กรณีที่ 1 :
delayPromiseเติมเต็มด้วย PromiseValue = 1:
async function delay1Second() {
return 1;
}
const result = await Promise.resolve(1);
const result = await newPromise;
const result = 1;
- กรณีที่ 2 :
delayPromiseถูกปฏิเสธ:
const result = await Promise.resolve(-1);
const result = await newPromise;
const result = -1;
อภิธานศัพท์:
- Settle:
Promise.[[PromiseStatus]]การเปลี่ยนแปลงจากpendingเป็นresolvedหรือrejected