我正在向 API 发出一个 HTTP 请求,以获取数组上的尽可能多的条目。
我想要做的是 console.log 每次都在做一个请求,但我无法在它发生时记录它,它会等待所有的完成,然后它一次记录它。
const data = ['one','two']
// This simulates the API response I have no control here
const mockAPI = (timeout) => {
return new Promise((resolve, reject) => setTimeout(() => resolve(), timeout))
}
let counter = 0
// For each entry in the array
const promises = data.map(() => {
return new Promise(async (resolve, reject) => {
// Keep track of how many request are we up to
counter++
// Log it
console.log(counter)
// Make the call to the API
await mockAPI(3000)
// Do something with the data from API...
resolve()
})
})
// I collect the results of all promises to processes it later on
const result = Promise.all(promises)
我想要的是记录:
1
等待三秒钟 - 显然,只要 API 需要然后:
2