promise.all 然后结构没有按预期工作

promise.all then structure not working as expected

我对 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 完成后,它会 return。 你的代码有3个promise,虽然有延迟部分,但是函数会直接完成。