我有这个代码。
const testArray = [1, 2, 3, 4, 5];
const test = async () => {
return Promise.resolve().then(() => {
console.log("Testing console log: ", new Date());
});
};
const testPromises = testArray.map(async (value) =>
new Promise((resolve) => setTimeout(resolve, 2000)).then(() => test())
);
const testResult = testPromises.reduce(
(p, testPromise) => p.then(() => testPromise),
Promise.resolve()
);
所以我期望通过 setTimeout 依次使用 testArray 映射函数做出的解析承诺,并以 2 秒的间隔记录消息。
但同时正在记录。
我不知道为什么这不起作用。
问题在于你的
testPromises
。它创建了 5 个承诺,并在 2 秒后同时在声明上解决。
const testPromises = testArray.map(async (value) =>
new Promise((resolve) => setTimeout(resolve, 2000)).then(() => test())
);
[Promise, Promise, Promise, Promise, Promise]
您真正想要的是创建一个使用
map
函数返回 Promise 的函数:
const testPromises = testArray.map((value) =>
() => new Promise((resolve) => setTimeout(resolve, 2000)).then(() => test())
);
然后调用该函数以按
reduce
顺序创建 Promise:
const testResult = testPromises.reduce(
(p, testPromise) => p.then(() => testPromise()),
Promise.resolve()
);
完整代码如下:
const testArray = [1, 2, 3, 4, 5];
// no need to use async when it returns a Promise explicitly
const test = () => {
return Promise.resolve().then(() => {
console.log("Testing console log: ", new Date());
});
};
// map into a funtion that returns a Promise instead
const testPromises = testArray.map((value) =>
() => new Promise((resolve) => setTimeout(resolve, 2000)).then(() => test())
);
// call the testPromise to chain onto the Promise
const testResult = testPromises.reduce(
(p, testPromise) => p.then(() => testPromise()),
Promise.resolve()
);