收盘价:偏离主题,缺少回报

时间:2018-07-19 00:02:32

标签: javascript node.js promise async-await

我有这个问题:

当我使用时:

async function createElement(req,res){
   const time1 = new Date().getTime();
   console.log("turn on time 1 ",time1)
   await new Promise((resolve) => setTimeout(resolve,1000));
   await new Promise((resolve) => setTimeout(resolve,1000));
   const time2 = new Date().getTime();
   console.log("turn on time 2 ",time2)
   console.log('result : ', time2 - time1);
}

结果是:

turn on time 1 1531957505408
turn on time 2 1531957507413
result : 2005

很好,但是当我尝试将promise.all与await一起使用

async function createElement(req,res){
let fn1 = () => {
    new Promise((resolve) => {

        setTimeout(() => {
            console.log("message from fn1")
            resolve()
       },1000)
    });
}
let fn2 = () => {
    new Promise((resolve) => {
        setTimeout(() => {
             console.log("message from fn2")
             resolve()
        },1000)

    });
}
const time1 = new Date().getTime();
console.log("turn on time 1 ",time1)
let responses = await Promise.all([fn1(),fn2()])
console.log("waiting for responses")
const time2 = new Date().getTime();
console.log("turn on time 2 ",time2)
console.log('result : ', time2 - time1);
}

结果是:

turn on time 1 1531957505408
turn on time 2  1531957505408
result 0
message from fn1
message from fn2

所以...在我需要将结果返回到fn1或/和fn2进行其他操作的情况下,我如何等待对promise的响应。全部

2 个答案:

答案 0 :(得分:0)

return功能的承诺

答案 1 :(得分:0)

您没有从fn1和fn2返回诺言。

async function createElement(req,res){
let fn1 = () => {
   return new Promise((resolve) => {

        setTimeout(() => {
            console.log("message from fn1")
            resolve()
       },1000)
    });
}
let fn2 = () => {
   return new Promise((resolve) => {
        setTimeout(() => {
             console.log("message from fn2")
             resolve()
        },1000)

    });
}
const time1 = new Date().getTime();
console.log("turn on time 1 ",time1)
let responses = await Promise.all([fn1(),fn2()])
console.log("waiting for responses")
const time2 = new Date().getTime();
console.log("turn on time 2 ",time2)
console.log('result : ', time2 - time1);
}

createElement();