【问题标题】:How to use await inside caolan async?如何在caolan async中使用await?
【发布时间】:2021-10-10 07:53:50
【问题描述】:

我想在async.Series 中使用await 方法

这是我的节点 js 代码

const async = require("async");

async.eachSeries(myArr, function (arr, callback) {

    let test = await db.collection('coll').findOne({ _id: arr }); //I couldn't use await here

    callback(null, test);

}, function (err) {
    console.log("Done");

});

我试过了


async.eachSeries(myArr, async function (arr, callback) {

    let test = await db.collection('coll').findOne({ _id: arr }); //It not working here

    callback(null, test);

}, function (err) {
    console.log("Done");

});

async.eachSeries(myArr, async.asyncify(async(function (arr, callback) {

    let test = await db.collection('coll').findOne({ _id: arr }); //It not working here

    callback(null, test);

})), function (err) {
    console.log("Done");

});

如果方法错误,请纠正我,或者让我知道如何在每个异步内部实现等待。

【问题讨论】:

    标签: node.js asynchronous async-await async.js


    【解决方案1】:

    正如asyncdocument所说:

    使用 ES2017 异步函数 Async 接受异步函数 接受一个节点样式的回调函数。但是,我们不会通过它们 回调,而是使用返回值并处理任何承诺 拒绝或抛出错误。

    如果你仍然把callback函数作为eachSeries 的回调函数的第二个参数传递,它就不会按预期工作了。只需删除 callback 并返回结果:

    async.eachSeries(myArr, async (arr) => { // remove callback parameter
      const test = await db.collection('coll').findOne({ _id: arr }); // wait the response
      // ...
      return test; // return response
    }, function (err) {
      console.log("Done");
    });
    

    或者只使用for...loop 而不是eachSeries

    // inside a async function
    for (const i of myArr) {
      const test = await db.collection('coll').findOne({ _id: arr });
      // Do something with `test`
    }
    
    console.log("Done");
    

    【讨论】:

      【解决方案2】:

      为什么要将回调与承诺混合使用?

      正确的方法是使用异步迭代器符号。

      如果不是第一次尝试将是有效的

      eachSeries(array, async function(arr, cb) {
         await ....
      });
      

      【讨论】:

        猜你喜欢
        • 2019-07-20
        • 2019-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-24
        • 2021-10-07
        • 2016-03-15
        • 2015-12-24
        相关资源
        最近更新 更多