【发布时间】:2020-06-27 13:52:01
【问题描述】:
MDN says for await...of 有两个用例:
for await...of语句创建了一个循环遍历 async 可迭代对象以及同步可迭代对象,...
我之前知道前者:使用Symbol.asyncIterator 的异步迭代。但我现在对后者感兴趣:同步迭代。
以下代码迭代同步可迭代对象 - 一组承诺。它似乎阻碍了每个承诺的兑现。
async function asyncFunction() {
try {
const happy = new Promise((resolve)=>setTimeout(()=>resolve('happy'), 1000))
const sad = new Promise((_,reject)=>setTimeout(()=>reject('sad')))
const promises = [happy, sad]
for await(const item of promises) {
console.log(item)
}
} catch (err) {
console.log(`an error occurred:`, err)
}
}
asyncFunction() // "happy, an error occurred: sad" (printed in quick succession, after about 5 seconds)
根据下面显示的逻辑,该行为似乎类似于依次等待每个承诺。这个说法正确吗?
async function asyncFunction() {
try {
const happy = new Promise((resolve)=>setTimeout(()=>resolve('happy'), 1000))
const sad = new Promise((_,reject)=>setTimeout(()=>reject('sad')))
const promises = [happy, sad]
for(let p of promises) {
const item = await p
console.log(item)
}
} catch (err) {
console.log(`an error occurred:`, err)
}
}
asyncFunction() // "happy, an error occurred: sad" (printed in quick succession, after about 5 seconds)
我之所以这么问,是因为这种代码模式有一个隐含的拒绝连接陷阱,Promise.all 和 Promise.allSettled 避免了这种错误,而且这种语言会明确支持这种模式对我来说似乎很奇怪。
window.addEventListener('unhandledrejection', () => {
console.log('unhandled rejection; `sad` was not being awaited at the time it rejected')
})
async function asyncFunction() {
try {
const happy = new Promise((resolve)=>setTimeout(()=>resolve('success'), 1000))
const sad = new Promise((_,reject)=>setTimeout(()=>reject('failure')))
const promises = [happy, sad]
for(let p of promises) {
const item = await p
console.log(item)
}
} catch (err) {
console.log(`an error occurred:`, err)
}
}
asyncFunction() // "unhandled rejection; `sad` was not being awaited at the time it rejected" (after about zero seconds), and then "happy, an error occurred: sad" (printed in quick succession, after about 5 seconds)
【问题讨论】:
-
您的问题到底是什么?您提供的示例似乎有效
-
我对具有同步迭代的
for await... of的描述是否正确,如果正确,那么该模式是否会发出未处理的拒绝错误? -
“它是否正确”不是问题。 “正确”就是你所说的。
-
您能否通过代码演示您描述的未处理拒绝错误的发射?
-
最终代码演示了它。正确在这种情况下具有明确的含义,因为我提供了代码来描述我认为它在做什么。如果行为符合我的代码,那么我的代码是正确的,否则我的理解是不正确的。此外,观察“正确”就是你所说的。 显然是不真实的。在这种情况下,正确具有明确定义的含义。