我对 Node 的东西还很陌生,所以如果它很基本,我提前道歉。
我试图触发一次函数,三个异步函数已经完成。这是我的方法:
第一个文件: ./promise.js var reqHandler = require('./asyncTesting'); var Promise = require('bluebird');
var listOfMed = ["med1","med2","med3"];
function postMethod() {
console.log("Post done");
}
reqHandler.reqHandler(listOfMed)
.then(function() {
console.log("Post done");
});
第二个文件:
./asyncTesting.js
var Promise = require('bluebird');
function function2() {
// all the stuff you want to happen after that pause
console.log("Requesting json for med2");
}
function callFunction(method){
if (method =="med2"){
setTimeout(function2, 3000);
}else{
console.log("Requesting json for "+method);
}
}
function reqHandler(listOfMed) {
return Promise.all(listOfMed.map(callFunction));
}
exports.reqHandler = reqHandler;
预期输出为:
Requesting json for med1
Requesting json for med3
Requesting json for med2
Post done
但是,我在控制台上真正得到的是:
Requesting json for med1
Requesting json for med3
Post done
Requesting json for med2
提前致谢
最佳答案
function callFunction(method){
return new Promise(function(resolve,reject){
if (method =="med2"){
setTimeout(function(){function2();resolve()}, 3000);
}else{
console.log("Requesting json for "+method);resolve();
}
});
}
Promise.all 表示当所有给出的 Promise 完成后,它将返回。 你的代码有三个promise,虽然有延迟部分,但函数会直接完成。
关于javascript - Promise.all 那么结构无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37788574/