// 使用 try...catch 实现多次重复尝试
const NUM_RETRIES = 3
async function test() {
for (let i = 0; i < NUM_RETRIES; ++i) {
try {
await fetch('http://google.com/this-throws-an-error')
// 如果请求成功,则跳出循环,否则继续重试直至三次
break
} catch (err) {}
}
}
注意点
在使用 await 命令时,有几个注意点:
最好将 await 命令放在 try...catch 代码块中。
多个 await 命令如果不存在继发关系,最好同时触发。
// 写法一
let [foo, bar] = await Promise.all([getFoo(), getBar()])
// 写法二
let fooPromise = getFoo()
let barPromise = getBar()
let foo = await fooPromise
let bar = await barPromise
async function func() {
for (let url of list) {
// 相继执行
await fetch(url)
}
}
为什么使用 forEach 和 for 循环执行多个异步操作会有不同表现,翻阅一些网上资料,找到 forEach 的 polyfill 实现如下:
Array.prototype.forEach = function(callback) {
// this represents our array
for (let index = 0; index < this.length; index++) {
// We call the callback for each entry
callback(this[index], index, this)
}
}
可以看出相当于 for 循环执行了这个异步函数,但是却是并发执行的,因为 callback 函数并没有进行异步执行。我们可以改造一个异步执行的 forEach 函数:
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array)
}
}