【问题标题】:Await in catch block fails inside forEach在 forEach 中的 catch 块中等待失败
【发布时间】:2018-11-08 17:30:24
【问题描述】:

我有一个类似数组的结构,它公开了异步方法。异步方法调用包含 try-catch 块,这些块反过来在捕获错误的情况下公开更多异步方法。我想了解为什么forEach 不能很好地与async/await 配合使用。

let items = ['foo', 'bar', 'baz'];

// Desirable behavior
processForLoop(items);
/* Processing foo
 * Resolved foo after 3 seconds.
 * Processing bar
 * Resolved bar after 3 seconds.
 * Processing baz
 * Resolved baz after 3 seconds.
 */

// Undesirable behavior
processForEach(items);
/* Processing foo
 * Processing bar
 * Processing baz
 * Resolved foo after 3 seconds.
 * Resolved bar after 3 seconds.
 * Resolved baz after 3 seconds.
 */

async function processForLoop(items) {
    for(let i = 0; i < items.length; i++) {
        await tryToProcess(items[i]);
    }
}

async function processForEach(items) {
    items.forEach(await tryToProcess);
}

async function tryToProcess(item) {
    try {
        await process(item);
    } catch(error) {
        await resolveAfter3Seconds(item);
    }
}

// Asynchronous method
// Automatic failure for the sake of argument
function process(item) {
    console.log(`Processing ${item}`);
    return new Promise((resolve, reject) =>
        setTimeout(() => reject(Error('process error message')), 1)
    );
}

// Asynchrounous method
function resolveAfter3Seconds(x) {
    return new Promise(resolve => setTimeout(() => {
        console.log(`Resolved ${x} after 3 seconds.`);
        resolve(x);
    }, 3000));
}

【问题讨论】:

    标签: javascript foreach async-await try-catch


    【解决方案1】:

    没有办法像这样使用 forEach 和 await - forEach 不能串行运行异步迭代,只能并行运行(即使那样,map 和 Promise.all 会更好)。相反,如果要使用数组方法,请使用 reduce 和 await 上一次迭代的 Promise 的分辨率:

    let items = ['foo', 'bar', 'baz'];
    
    processForEach(items);
    
    async function processForLoop(items) {
      for (let i = 0; i < items.length; i++) {
        await tryToProcess(items[i]);
      }
    }
    
    async function processForEach(items) {
      await items.reduce(async(lastPromise, item) => {
        await lastPromise;
        await tryToProcess(item);
      }, Promise.resolve());
    }
    
    async function tryToProcess(item) {
      try {
        await process(item);
      } catch (error) {
        await resolveAfter3Seconds(item);
      }
    }
    
    // Asynchronous method
    // Automatic failure for the sake of argument
    function process(item) {
      console.log(`Processing ${item}`);
      return new Promise((resolve, reject) =>
        setTimeout(() => reject(Error('process error message')), 1)
      );
    }
    
    // Asynchrounous method
    function resolveAfter3Seconds(x) {
      return new Promise(resolve => setTimeout(() => {
        console.log(`Resolved ${x} after 3 seconds.`);
        resolve(x);
      }, 3000));
    }

    另外请注意,如果函数中唯一的await 恰好在函数返回之前,您最好只返回 Promise 本身,而不是让函数为 async。

    【讨论】:

    • (即使那样,map 和 Promise.all 会更好)...在我的情况下,两种异步方法都涉及 IO,所以除非我弄错了,否则使用 Promise.all 会是一个坏主意。谢谢,帮了我很多忙。
    • 这只是在你想并行运行迭代的情况下,但你明确表示你想串行运行它们,因此reduce方法。
    • 确实没有理由在async 函数中更喜欢reduce 模式而不是for of。
    【解决方案2】:

    我想了解为什么forEach 不能很好地与async/await 配合使用。

    如果我们认为async 只是返回承诺的函数的语法糖,那就更容易了。

    items.forEach(f) 需要一个函数 f 作为参数,它在返回之前对每个项目一次执行一个。它忽略了f 的返回值。

    items.forEach(await tryToProcess) 是废话,相当于Promise.resolve(tryToProcess).then(ttp =&gt; items.forEach(ttp))

    在功能上与items.forEach(tryToProcess)没有区别。

    现在tryToProcess 返回一个promise,但forEach 忽略了返回值,正如我们已经提到的,所以它忽略了那个promise。这是个坏消息,并且可能导致未处理的拒绝错误,因为所有承诺链都应该返回或以catch 终止以正确处理错误。

    这个错误相当于忘记了await。不幸的是,没有array.forEachAwait()。

    items.map(f) 稍微好一点,因为它从f 的返回值中创建了一个数组,在tryToProcess 的情况下,它会给我们一个promise 数组。例如。我们可以这样做:

    await Promise.all(items.map(tryToProcess));
    

    ...但是每个项目上的所有tryToProcess 调用都将并行彼此执行。

    重要的是,map 并行运行它们。 Promise.all 只是等待它们完成的一种方式。

    通常...

    我总是在async 函数中使用for of 而不是forEach:

    for (const item of items) {
      await tryToProcess(item);
    }
    

    ...即使循环中没有await,以防我稍后添加一个,以避免这种脚枪。

    【讨论】:

      猜你喜欢
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 2020-01-01
      • 1970-01-01
      • 2019-06-29
      • 2023-03-03
      相关资源
      最近更新 更多