【问题标题】:promise.all then structure not working as expectedpromise.all 然后结构无法按预期工作
【发布时间】:2016-10-13 19:15:35
【问题描述】:

我对 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

提前致谢

【问题讨论】:

  • 要使listOfMed.map(callFunction) 具有任何值,您最好确保callFunction 有返回值。

标签: javascript node.js asynchronous promise bluebird


【解决方案1】:
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,虽然有延迟部分,但是函数会直接完成。

【讨论】:

  • 你说得对。我还没有意识到超时是通过 function2 作为参数来执行的。谢谢!真的很有用
猜你喜欢
  • 2014-12-06
  • 2017-12-23
  • 1970-01-01
  • 2020-07-16
  • 2021-04-02
  • 1970-01-01
  • 2017-08-28
  • 2022-11-23
相关资源
最近更新 更多