节点使用aprom.all异步/等待 [英] Node async/await with promise.all

查看:183
本文介绍了节点使用aprom.all异步/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个简单的JS程序中,我需要让asyncOperation2和asyncOperation3与asyncOperation1一起顺序执行.这意味着我需要进行以下操作:

In a simple JS program, I need to have asyncOperation2 and asyncOperation3 execute sequentially along with asyncOperation1. Meaning I need the following to happen:

1) order of execution as  1,2,3 or 2,3,1
2) then after step 1. I need to preform an operation on the result of 1,2,3

这是我到目前为止所拥有的(它将在Node中运行).但是我无法如上所述执行操作顺序.

Here's what I have so far(this will run in Node). But I cannot get the order of operations to happen as I described above.

const App = {
    total: 0,

    init: function () {
        // I want to run all 3 operations. (with 2 and 3 happening sequentially)
        Promise.all([App.asyncOperation1(1000), App.combine2and3()])
            .then((total) => {
                // then I want to use the result of all 3 operations
                console.log(`total from top: ${total}`);
            })
    },

    asyncOperation1: function (time) {
        return new Promise(function (resolve, reject) {
            var intervalID = setTimeout(function () {
                resolve(time);
            }, time);
        });
    },

    asyncOperation2: async function (time) {
        setTimeout(function () {
            return time;
        }, time);
    },

    asyncOperation3: async function (time) {
        setTimeout(function () {
            return time;
        }, time);
    },

    combine2and3: async function () {
        var value2 = await App.asyncOperation2(2000);
        var value3 = await App.asyncOperation3(1000);
        console.log(`value2: ${value2}`)
        console.log(`value3: ${value3}`)
        console.log(`summed total ${value2 + value3}`);
        return value2 + value3;
    },
};

App.init();

实际结果:

value2: undefined
value3: undefined
summed total NaN
total from top: 1000,NaN

所需结果:

value2: 2000
value3: 1000
summed total 3000
total from top: 1000,3000

推荐答案

问题是asyncOperation2()asyncOperation3()返回承诺 (因为它们的async声明)没有可解析的值(因此是undefined),因为这些函数没有自己的返回值.

The problem is that asyncOperation2() and asyncOperation3() return a promise (because of their async declaration) that has no resolved value (thus it's undefined) because those functions don't have their own return value.

asyncOperation2: async function (time) {
    setTimeout(function () {
        return time;     // this just returns back into the timer sub-system
    }, time);
    // there is no return value for your function here
    // thus the promise the async function returns has an undefined resolved value
},

setTimeout()内部返回不是函数的返回值.那只是返回到函数内部返回很长时间之后的计时器内部.请记住,setTimeout()是非阻塞的.它计划一些代码在将来的某个时间运行,然后立即返回,然后您的函数完成并返回(在setTimeout()被触发之前).因此,然后在以后的某个时间,您的setTimeout()触发,您从该回调中返回一个值,并且该值仅返回到计时器子系统,而不是您的任何代码或任何promise.

Returning from inside the setTimeout() isn't the function's return value. That's just a return back into the timer innards that happens long after the function itself has returned. Remember, setTimeout() is non-blocking. It schedules some code to run sometime in the future and then returns immediately and your function then finishes and returns (before setTimeout() has fired). So, then sometime later, your setTimeout() fires and you return a value from that callback and that value just goes back into the timer sub-system, not to any of your code or to any promise.

将这两个功能更改为此:

Change those two functions to this:

function delay(t, v) {
   return new Promise(resolve => {
       setTimeout(resolve.bind(null, v));
   }, t);
}

asyncOperation2: function (time) {
    return delay(time, time);
},

asyncOperation3: function (time) {
    return delay(time, time);
},

现在,您可以使用一些函数来返回以所需值解析的promise.请注意,由于您未在函数内使用await并且已经在创建自己的返回保证,因此无需将它们声明为async.

Now you have functions that return a promise that is resolved with the desired value. Note, there's no need for them to be declared async either since you aren't using await inside the functions and you're already creating your own promise to return.

这篇关于节点使用aprom.all异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆