[英]Dynamically generate a chain of promises with async/await
Say, I need to repeat an AJAX request N times sequentially. 说,我需要按顺序重复一次AJAX请求。
Normally (ie without async/await), I would use reduce
to chain promises: 通常(即没有异步/等待),我会使用reduce
来链接承诺:
function timeout (ms = 1000) { return new Promise(resolve => setTimeout(resolve, ms)) } function request (message, ms = 1000) { return timeout(ms).then(() => console.log(message)) } function makeArray (i) { return new Array(i).fill(null); } makeArray(5).reduce( (promise, _, i) => promise.then(() => request(i)), Promise.resolve() )
How do I rewrite this code with async/await? 如何使用async / await重写此代码?
Instead of promise.then(() => request(i))
I want to do await request(i)
. 而不是promise.then(() => request(i))
我想await request(i)
。
All my attempts ended up running promises in parallel. 我所有的尝试最终都是并行运行承诺。 I want sequentially. 我想顺序。
Remember await
can only be invoked from a an async
function. 记住await
只能从async
函数调用。
Here I've just wrapped inside a function run
, it could even be an IIFE.. 在这里我刚刚包含在一个函数run
,它甚至可能是一个IIFE ..
In most cases when you start using async / await
, you'll be calling from another async
function anyway, so this little run
stub wouldn't be required. 在大多数情况下,当你开始使用async / await
,无论如何你将从另一个async
函数调用,所以不需要这个小run
存根。
function timeout (ms = 1000) { return new Promise(resolve => setTimeout(resolve, ms)) } function request (message, ms = 1000) { return timeout(ms).then(() => console.log(message)) } async function run() { for (let trys = 0; trys < 5; trys ++) { await request(trys); } } run();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.