我想制作一個 API 東西來加載 pokemons 串列以及它的影像。得到了串列,并想確保圖片上的序列對于這個 i console.log 是正確的。而且順序不對。在不同的地方嘗試了一些異步等待,但無法弄清楚如何獲得正確的訂單 https://codepen.io/DeanWinchester88/pen/ExvxdxX
Promise.all(arrForFetch)
.then(files => {
files.forEach(file => {
console.log("files", file)
process(file.json())
})
.catch(err => console.log("tobie pizda ucziekaj"))
})
let process = (prom) => {
console.log(prom)
prom.then(data => {
console.log(data.name)
})
}
uj5u.com熱心網友回復:
const results = await Promise.all(arrForFetch)
// do something with results array
你的問題是它file.json()是異步的,所以需要從回圈中作為另一個 Promise all 回傳,或者在回圈中等待。您可以映射承諾。
Promise.all(arrForFetch)
.then( files =>{
const more = files.map(file=>file.json().then(process))
return Promise.all(more)
})
.catch(err => console.log("tobie pizda ucziekaj"))
Promise.all(arrForFetch)
.then( async files =>{
for(const i=0; i<files.length; i ){
console.log("files", files[i])
process( await files[i].json() )
}
})
.catch(err => console.log("tobie pizda ucziekaj"))
uj5u.com熱心網友回復:
假設我有一個 API 呼叫,它從資料庫回傳所有用戶并需要一些時間才能完成。
// First promise returns an array after a delay
const getUsers = () => {
return new Promise((resolve, reject) => {
return setTimeout(
() => resolve([{ id: 'jon' }, { id: 'andrey' }, { id: 'tania' }]),
600
)
})
}
現在有另一個呼叫依賴于存在于整個用戶陣列中的一些資訊。
// Second promise relies on the result of first promise
const getIdFromUser = (user) => {
return new Promise((resolve, reject) => {
return setTimeout(() => resolve(user.id), 500)
})
}
第三個呼叫修改了第二個呼叫。
// Third promise relies on the result of the second promise
const capitalizeIds = (id) => {
return new Promise((resolve, reject) => {
return setTimeout(() => resolve(id.toUpperCase()), 200)
})
}
我可能會嘗試運行第一個呼叫,然后使用 for...of 回圈運行依賴它的后續呼叫。
const runAsyncFunctions = async () => {
const users = await getUsers()
for (let user of users) {
const userId = await getIdFromUser(user)
console.log(userId)
const capitalizedId = await capitalizeIds(userId)
console.log(capitalizedId)
}
console.log(users)
}
runAsyncFunctions()
但是,這將是我的輸出:
jon
JON
andrey
ANDREY
tania
TANIA
(3) [{…}, {…}, {…}]
我可以使用 Promise.all() 來運行第一個函式,然后是第二個函式,然后是第三個函式。
const runAsyncFunctions = async () => {
const users = await getUsers()
Promise.all(
users.map(async (user) => {
const userId = await getIdFromUser(user)
console.log(userId)
const capitalizedId = await capitalizeIds(userId)
console.log(capitalizedId)
})
)
console.log(users)
}
輸出:
(3) [{…}, {…}, {…}]
jon
andrey
tania
JON
ANDREY
TANIA
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321727.html
標籤:javascript 异步 拿来
上一篇:異步SQLalchemy:訪問急切加載的空關系會觸發新的延遲加載,引發錯誤
下一篇:異步等待不等待輸出回傳
