我想列出每個名字旁邊的口袋妖怪和圖片。我從 api 獲取串列,然后將所有名稱組合到通用 APi 地址并制作獲取陣列。我的問題是回傳的串列是無序的,它有異步等待和 console.log 名稱(行程函式)。但它不起作用/你能幫我嗎? 代碼筆鏈接
(async function(){
await Promise.all(arrForFetch)
.then(async files =>{
for(let i = 0; i < files.length; i ){
// console.log("files", files[i])
process( await files[i].json())
}
// files.forEach( file =>{
// console.log("files", file)
// process( file.json() )
// })
// .catch(err => console.log("tobie pizda ucziekaj"))
})
.catch(err => console.log("tobie pizda ucziekaj"))
})();
let process = (prom) => {
prom.then( data =>{
console.log(data.id)
})
}
uj5u.com熱心網友回復:
默認情況下,回傳值Promise.all將保持給定的順序。因此,在您的情況下,在Promise.allforarrForFetch完成后,您將擁有一個有序的回應資料陣列。
您似乎正在嘗試將此回應資料轉換為JSON格式,然后顯示單個 pokemon 的 ID。您也可以在Promise.all此處使用 a 。我在以下代碼段中稍微修改了您的實作:
let arrForFetch = pokeNames.map(elem => fetch(" https://pokeapi.co/api/v2/pokemon/" `${elem}` ) );
//multiple APis fetching
Promise.all(arrForFetch).then((jsonData) => {
// creating array to convert each of the data entries to JSON format
let JsonConversionArray = jsonData.map(data => data.json());
// Using Promise.all similar to previous implementation.
Promise.all(JsonConversionArray).then((data) => {
const idArray = data.map((pokemon) => pokemon.id);
console.log(idArray);
})
}).catch((err) => {
console.log(err);
})
但是,如果您更喜歡自己的解決方案,即沒有Promise.allJSON 轉換,您可以按如下方式進行:
let arrForFetch = pokeNames.map(elem => fetch(" https://pokeapi.co/api/v2/pokemon/" `${elem}` ) );
//multiple APis fetching
Promise.all(arrForFetch).then((files) => {
// Iterating through files array
for (let i=0; i<files.length; i ) {
// You need not use await here because you are already using a then
// clause in the process() function
process(files[i].json())
}
}).catch((err) => {
console.log(err);
});
// Function to display the id of the pokemon from the JSON
function process (prom) {
prom.then(data => { console.log(data.id) })
}
uj5u.com熱心網友回復:
您的實作存在一些問題,讓我們逐步修復它們:
您定義了arrForFetch,到目前為止一切順利。
let arrForFetch = pokeNames.map(elem => fetch(" https://pokeapi.co/api/v2/pokemon/" `${elem}` ))
現在,你有一個陣列,這個陣列的每個元素現在都是一個承諾,需要被決議或拒絕。因此,Promise.all()在let arrForFetch沒有定義任何函式的情況下使用方法檢查它們:
function process(prom) => {
prom.then(consoe.log).catch(console.error)
}
const arrForFetch = pokeNames.map(elem => fetch(" https://pokeapi.co/api/v2/pokemon/" `${elem}` ))
Promise.all(arrForFetch)
.then(result => result.forEach(file => process(file.json())))
.catch(console.error)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321724.html
標籤:javascript 异步 承诺
