微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

需要确认回调和错误如何在 async.each 中使用 try-catch 块

如何解决需要确认回调和错误如何在 async.each 中使用 try-catch 块

我已经对此进行了几天的修补,并看到了许多不同的模式。在某些方面,我感到比刚开始时更困惑!

itemsArr 是项目对象 (itemObj) 的列表,其中包含有关每个项目的摘要信息。每个 itemObj 包含一个 itemId,它兼作 API slug 目录。因此,我需要遍历 itemsArr,为每个项目进行 API 调用,并返回更新后的数组,其中包含从每个 API 调用中检索到的所有详细信息。完成后,我想将扩充数组 enrichedItemsArr 记录到持久存储中。

API 调用返回的顺序无关紧要,因此使用 async.each。如果发生错误,我也不想中断执行。我的问题:

  1. 在执行 enrichArr() 之前正在打印“完成丰富的数组”-> 为什么 await async.each... 中的 enrichArr() 没有阻塞?
  2. 我在内部 try-catch 中收到 TypeError: callback is not a function。不知道为什么。
  3. 如果我在内部 try-catch 中将 err 传递给 callback(),会停止执行吗?
  4. 我应该将 itemsArr 作为第二个参数传递给 processDone 吗?有没有办法从 itemsArr 方法返回 main()processDone()
  5. 传递给最终回调的 err 是否包含错误数组?
const main = async () => {
    const itemsArr = items.getArr(); // --> retrieves locally cached itemsArr
    const enrichedItemsArr = await enrichArr(itemsArr); // --> handling the async iterator stuff below
    await logToDB(enrichedItemsArr); // --> helper function to log enriched info to database
    console.log('Done enriching array');

};

const enrichArr = async (itemsArr) => {

    // Outer try-catch
    try {

        const processItem = async (item,callback) => {

            // Inner try-catch
            try {
                const res = await doSomethingAsync(itemID);
                item.res = res;
                callback(); // --> currently getting `TypeError: callback is not a function`
            } catch (err) {
                item.err = err;
                callback(err); // --> not 100% sure what passing err here does...
            }

        };

        const processDone = (err,itemsArr) => {
            if (err) console.error(err); // --> Is err an array of errors or something?
            return itemsArr; // --> how do I return this to main()?
        };

        await async.each(itemsArr,processItem,processDone);

    } catch (err) {
        throw err; // --> if async.each errors,throw
    }

};

解决方法

希望这对您来说是一个很好的答案。

  1. 为什么在enrichArr() 中await async.each... 没有阻塞?

根据文档,async.each 只会在省略回调时返回承诺

each

您包含回调,async.each 不会返回承诺,也不会使用 async/await 阻止您的代码

  1. 我收到 TypeError:回调不是内部 try-catch 中的函数。不知道为什么。

你的 processItem 应该是一个普通的函数,这样做我可以使用 callback,当你使用异步函数时,库似乎不高兴

const processItem = (item,callback) => {
 const itemId = item;
 // Inner try-catch
 try {
     doSomethingAsync((res) => {
         item.res = res;
         callback()
     });
 } catch (err) {
     item.err = err;
     callback(err); // --> not 100% sure what passing err here does...
 }

};

  1. 如果我在内部 try-catch 中将 err 传递给 callback(),会停止执行吗?

是的,它会抛出错误

  1. 我应该将 itemsArr 作为第二个参数传递给 processDone 吗?有没有办法从 processDone() 方法将 itemsArr 返回给 main()?

如果你想让主方法知道需要等待,你将无法使用 processDone。

ItemsArr 是一个对象,你可以修改这个对象,main 方法应该可以看到那些变化,如果你想使用 array.each,没有其他方法。

也许异步库中有另一种方法可以让您返回一个新数组。

也许地图是一个不错的选择map

  1. 传递给最终回调的 err 是否包含错误数组?

不,这是让库知道需要抛出错误的一种方式。

我创建了一个片段来让你玩代码

const async = require('async');

const logToDB = async (items) => {
    items.forEach((item) => console.log(JSON.stringify(item)))
}

const doSomethingAsync = (callback) => {
    setTimeout(() => {
        console.log('processing data')
        callback()
    },1000);
}
const main = async () => {
    const itemsArr = [
        {
            itemId: '71b13422-2582-4975-93c9-447b66764daf'
        },// {
        //     errorFlag: true
        // },{
            itemId: '8ad24197-7d30-4514-bf00-8068e216e90c'
        }
    ]; // --> retrieves locally cached itemsArr
    const enrichedItemsArr =  await enrichArr(itemsArr); // --> handling the async iterator stuff below
    await logToDB(enrichedItemsArr); // --> helper function to log enriched info to database
    console.log('Done enriching array');

};

const enrichArr = async (itemsArr) => {

    // Outer try-catch
    try {

        const processItem =  (item,callback) => {
            console.log('item: ',item);
            const itemId = item;
            // Inner try-catch
            try {
                if (item.errorFlag) {
                    return callback('Test error');
                }
                doSomethingAsync((res) => {
                    item.res = res;
                    callback()
                });
            } catch (err) {
                item.err = err;
                callback(err); // --> not 100% sure what passing err here does...
            }

        };

        await async.each(itemsArr,processItem);
        return itemsArr;
    } catch (err) {
        console.log('Error occurred');
        throw err; // --> if async.each errors,throw
    }
};
main();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。