gpt4 book ai didi

javascript - Node 异步/等待与 promise.all

转载 作者:搜寻专家 更新时间:2023-10-31 23:10:48 25 4
gpt4 key购买 nike

在一个简单的 JS 程序中,我需要让 asyncOperation2 和 asyncOperation3 与 asyncOperation1 一起顺序执行。这意味着我需要发生以下情况:

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 中运行)。但是我无法按照上面描述的那样获得操作顺序。

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()还一个 promise (因为它们的 async 声明)没有解析值(因此它是 undefined )因为这些函数没有自己的返回值。

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 。

将这两个函数改成这样:

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 。请注意,不需要声明它们 async要么因为你没有使用 await在函数内部,您已经创建了自己的返回 promise 。

关于javascript - Node 异步/等待与 promise.all,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49946978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com