如下面的例子,因为fetch是异步的,所以没等fetch返回数据TODO()就执行了,我希望让TODO()在所有fetch都返回数据后再执行,该如何处理?希望大神能给个思路
function fetchAll(){
for(var i=0; i<10; i++){
fetch('http://127.0.0.1').then(function(res) {
if (res.ok) {
try {
res.json().then(function(data) {
console.log(data)
})
} catch(e){
console.warn(e)
}
}
})
}
}
fetchAll()
TODO()
既然你以及用 Promise 了,你应该了解一下
Promise.all
方法