在JavaScript中循环通过一系列承诺
我有一些代码可以通过一系列承诺循环,并输出值。
function wait(seconds) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(seconds);
}, seconds * 1000);
});
}
const promises = [
wait(1),
wait(3),
wait(2),
wait(4),
wait(5),
];
for (var promise of promises) {
promise.then(seconds => console.log(`waited ${seconds} seconds`));
}
这样的问题是,承诺结果不会以数组的顺序记录。我的预期结果是:
Waited 1 seconds
Waited 3 seconds
Waited 2 seconds
Waited 4 seconds
Waited 5 seconds
结果是:
Waited 1 seconds
Waited 2 seconds
Waited 3 seconds
Waited 4 seconds
Waited 5 seconds
所以我想拥有这样的事情,
function wait(seconds) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(seconds);
}, seconds * 1000);
});
}
const promises = [
wait(1),
wait(3),
wait(2),
wait(4),
wait(5),
];
for (var promise of promises) {
// When the promise is resolved, log `Waited ${seconds} seconds`
}
我该怎么做?
I have some code that loops through an array of promises, and outputs the value.
function wait(seconds) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(seconds);
}, seconds * 1000);
});
}
const promises = [
wait(1),
wait(3),
wait(2),
wait(4),
wait(5),
];
for (var promise of promises) {
promise.then(seconds => console.log(`waited ${seconds} seconds`));
}
The issue with this is that the promise results don't get logged in the order of the array. My expected result is this:
Waited 1 seconds
Waited 3 seconds
Waited 2 seconds
Waited 4 seconds
Waited 5 seconds
And the result was this:
Waited 1 seconds
Waited 2 seconds
Waited 3 seconds
Waited 4 seconds
Waited 5 seconds
So I would like to have something like this
function wait(seconds) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(seconds);
}, seconds * 1000);
});
}
const promises = [
wait(1),
wait(3),
wait(2),
wait(4),
wait(5),
];
for (var promise of promises) {
// When the promise is resolved, log `Waited ${seconds} seconds`
}
How would I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不希望计时器一次开始全部启动,则不应一次进行所有这些
等待
一次调用。相反,只有在上一个产生的承诺得到解决时,只有下一个电话:如果您 do 想要同时开始所有承诺,并且想要等待它们的全部在开始输出结果之前解决,然后使用
Promise> Promise .all
:如果您 do 希望所有承诺要同时开始,并且想等待它们仅在上一个解决方案后才解决,请使用
等待
:If you don't want the timers to start all at once, you shouldn't make all those
wait
calls at once. Instead only make the next call when the previous one's resulting promise has resolved:If you do want all promises to start at the same time, and want to wait for all of them to resolve before starting to output the results, then use
Promise.all
:If you do want all promises to start at the same time, and want to wait for them to resolve only after the previous one resolved, then use
await
:丹尼尔·怀特(Daniel A.
Daniel A. White is right - use Promise.all() - something like this: