首页 > 解决方案 > 使用 promise 等待 async.maplimit

问题描述

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

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:无法读取与 _waitForMe 相关的未定义属性“then”

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

跳过回调会产生相同的未定义问题“然后”

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

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

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

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

但这会导致(节点:567)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“长度”。

我仍然无法理解为什么在不涉及回调的情况下 async.mapLimit 的返回是未定义的。

更新 2

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

标签: node.jspromise

解决方案


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

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

推荐阅读