gpt4 book ai didi

javascript - 为什么这个简单的 async - promise - reduce 代码有效?

转载 作者:行者123 更新时间:2023-11-30 19:27:09 25 4
gpt4 key购买 nike

为什么这段代码运行完美?我不知道为什么这段代码有效。

loop 方法不返回任何内容,因此 accumulator 需要为 null,此代码不能运行。

const arr = [1, 2, 3, 4];

const awaitFunc = (val) => new Promise(function (resolve, reject) {
setTimeout(function () {
console.log('awaitFunc', val);
resolve();
}, 500);
});

const start = async () => {
console.log('start');

await arr.reduce(async (promise, val, index) => {
await promise;

console.log('reduce loop', val);

await awaitFunc(val);
}, Promise.resolve());

console.log('end');
};

start();

结果是这样的

start
reduce loop 1
(500ms)
awaitFunc 1
reduce loop 2
(500ms)
awaitFunc 2
reduce loop 3
(500ms)
awaitFunc 3
reduce loop 4
(500ms)
awaitFunc 4
end

最佳答案

async 函数会自动返回一个 Promise。如果函数包含 await,则 Promise 将在所有 await 完成后解析(并且解释器到达函数 block 的底部)。因为累加器是一个 async 函数,它会自动返回一个 Promise,所以 awaiting last 迭代返回的 Promise 的解析(累加器的最后一次运行)是有道理的。

所以,

 await arr.reduce(async (promise, val, index) => {
await promise;

console.log('reduce loop', val);

await awaitFunc(val);
}, Promise.resolve());

相当于

await arr.reduce((promise, val, index) => {
return promise.then(() => {
console.log('reduce loop', val);
return awaitFunc(val);
// ^^^^^^^ returned end of Promise chain, so accumulator promise in next reduce loop will resolve
// once above promise resolves
});
}, Promise.resolve());

 await arr.reduce((promise, val, index) => {
// just for illustration, don't use the explicit Promise construction antipattern
return new Promise((resolve) => {
// await promise;
promise.then(() => {
console.log('reduce loop', val);
// await awaitFunc(val);
awaitFunc(val).then(resolve)
// ^^^^^^^ Accumulator promise in next reduce loop will resolve
});
});
}, Promise.resolve());

const arr = [1, 2, 3, 4];

const awaitFunc = (val) => new Promise(function (resolve, reject) {
setTimeout(function () {
console.log('awaitFunc', val);
resolve();
}, 500);
});

const start = async () => {
console.log('start');

await arr.reduce((promise, val, index) => {
// just for illustration, don't use the explicit Promise construction antipattern
return new Promise((resolve) => {
// await promise;
promise.then(() => {
console.log('reduce loop', val);
// await awaitFunc(val);
awaitFunc(val).then(resolve)
});
});
}, Promise.resolve());

console.log('end');
};

start();

关于javascript - 为什么这个简单的 async - promise - reduce 代码有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56789697/

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