簡體   English   中英

使用Promise將元素推入數組

[英]Pushing an Element into an Array Using Promises

當我console.log我的數組時,它保持為空,因此我無法使用我的代碼將元素推入數組。 我可以在函數外部執行此操作,但是不知道我在諾言中做錯了什么。 我是新來的諾言。 感謝您的提示:

function fetchApiData(num) {
 let arr = []; 

for(let i = 0; i < num; i++) {
  fetch('https://dog.ceo/api/breeds/image/random')
  .then(response => response.json())
  .then(responseJson => console.log(responseJson.message))
  .then(responseJson => arr.push(responseJson.message));
  console.log(arr);
  }
  console.log(arr);  
  // how do I change console.log to push value into an array? 
}

您的問題是解決的順序。 即,當您的代碼執行時,將發生以下情況:

0.)Arr = []

1.)開始循環

2.)發起承諾

3.)日志地址

4.)循環完成

5.)日志地址

6.)在將來的某個不確定的時間點(幾毫秒后),您的承諾會一次解決,每次都會將元素添加到數組中。

嘗試捕獲數組中的promise並使用

Promise.all(promiseArr).then(()=>{
    console.log(arr)
})

Promise.all將等到數組中的所有promise完成后再執行,因此您將能夠記錄已完成的數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM