简体   繁体   English

然后所有的结构都无法按预期工作

[英]promise.all then structure not working as expected

I am pretty new on Node stuff so I do apologise in advance if it is quite basic. 我对Node的知识还很陌生,所以如果它很基础,我会提前道歉。

I am trying to trigger a function once, three asynchronous functions have already finished. 我试图触发一个函数,因为三个异步函数已经完成。 This is my approach: 这是我的方法:

First file: ./promise.js var reqHandler = require('./asyncTesting'); 第一个文件:./promise.js var reqHandler = require('./ asyncTesting'); var Promise = require('bluebird'); var Promise = require('bluebird');

var listOfMed = ["med1","med2","med3"];

function postMethod() {
    console.log("Post done");
}

reqHandler.reqHandler(listOfMed)
    .then(function() {
    console.log("Post done");
});

The second file: 第二个文件:

./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;

The expected output would be: 预期的输出将是:

Requesting json for med1
Requesting json for med3
Requesting json for med2
Post done

However, what I really got on console is: 但是, 我真正在控制台上得到的是:

Requesting json for med1
Requesting json for med3
Post done
Requesting json for med2

Thanks in advance 提前致谢

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 means when all promises given finished,it will return. Promise.all表示当所有的诺言完成时,它将返回。 Your code has three promise,though there is a delayed part,but function will finished directly. 您的代码有三个承诺,尽管有一个延迟部分,但是功能将直接完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM