【发布时间】: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'中。