【问题标题】:Wait for async.maplimit using promise使用 promise 等待 async.maplimit
【发布时间】:2020-02-27 14:44:15
【问题描述】:

我正在尝试使用 promise 来等待 async.mapLimit。我用它同时运行多个 shell 脚本,我想等待所有脚本都完成执行,然后再继续通过日志“结束”。但我在使用时总是得到一个 undefined承诺的返回值。

var myArray = [5,1,2,3,4];

const async = require('async');
const exec = require('child_process').exec;

function understandPromise() {

    const _waitForMe = async.mapLimit(myArray, 16, doSomeThing, function(err, results){
        console.log(results.length, 'should equal (doSomeThing)', myArray.length);
        console.log('err',err);

    });

    // This also gives undefined
    //const _waitForMe = async.mapLimit(myArray, 16, doSomeThing).then(a,b);
    _waitForMe.then(a,b);

    console.log('the end');

}

function doSomeThing(item, callback){

    let runCmd = './test.sh ' + item;
    console.log('before', runCmd);
    exec(runCmd, function (error, stdout, stderr) {
        console.log('error', error);
        console.log('stderr', stderr);
        console.log('stdout', stdout);
        console.log('after', runCmd);
        callback(null, item); // or actually do something to item
    });

}

understandPromise();

TypeError: Cannot read property 'then' of undefined 与 _waitForMe 相关

为什么 mapLimit 不返回一个承诺?我意识到我在这里做了一些根本错误的事情,但我不知道是什么。我也可以考虑其他不涉及承诺的解决方案。

跳过回调会产生同样的问题 'then' of undefined

const _waitForMe = async.mapLimit(myArray, 16, doSomeThing);

类似这样的 SO 问题只会给出错误async.mapLimit with Promise

cmets 后更新 1 评论者建议这样做:

async function understandPromise() {
        let results = await async.mapLimit(myArray, 8, doSomeThing);
        console.log('results', results.length);
        console.log('the end');
}

但这会导致 (node:567) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined。

我还是不明白为什么在不涉及回调的情况下,async.mapLimit 的返回是未定义的。

更新 2

我从 cmets 得到了这个,但最后是异步模块处于旧版本 1.5.2 而不是较新的 3.2.0

【问题讨论】:

  • 你放入 cmets 的版本,工作 fine (当然,在这个演示中没有一个 shell 脚本会成功,但这无关紧要)。检查async包的版本是最新的吗?
  • @trincot 我试过你的代码,但在所有的 shell 脚本/你的睡眠完成之前,它仍然运行通过 console.log('the end')。 (async@3.2.0)
  • 当然,你是同步执行的。如果你不想这样,那么你必须把它放在函数'b'中。

标签: node.js promise


【解决方案1】:

问题是您在函数末尾传递回调。文档清楚地写着it returns a promise, if no callback is passed。删除function(err, results),它应该开始返回一个promise。

const results = await async.mapLimit(myArray, 16, doSomeThing);
console.log(results.length, 'should equal (doSomeThing)', myArray.length);

【讨论】:

  • 你是这个意思吗? var _waitForMe = async.mapLimit(myArray, 16, doSomeThing); _waitForMe.then(a,b);这也变得未定义
  • @bits 对不起,你是什么意思?我也添加了代码。
  • const 结果 = await async.mapLimit(myArray, 16, doSomeThing); SyntaxError: await 只在 async 函数中有效,所以这不起作用
  • @bits,当然你需要把它放在一个async函数中;那不用说了。您可以像 IIFE 一样立即执行该异步函数。
  • async function understandPromise() {
猜你喜欢
  • 2019-12-28
  • 2017-10-09
  • 2020-01-15
  • 2016-12-18
  • 1970-01-01
  • 2022-07-20
  • 2021-10-04
  • 2016-05-03
  • 2018-12-02
相关资源
最近更新 更多