簡體   English   中英

Promise.all錯誤:未捕獲(承諾)TypeError:# <Promise> 是不可迭代的

[英]Promise.all Error: Uncaught (in promise) TypeError: #<Promise> is not iterable

因此,我需要點擊2個API,並在我分派動作之前等待這兩個響應返回。

我正在使用Promise.all但是Promise.all以下錯誤:

index.js:51未捕獲(承諾)TypeError:#在Function.all()不可迭代

const fetchPrices = () => Promise.resolve(getPrices());
const fetchSupplies = () => Promise.resolve(getSupply());
const fetchAll = () => Promise.all(fetchPrices(), fetchSupplies()).then((resultsArray) => {
  return resultsArray;
});

// GET coins from coinmarketcap Pro API v1.
export const startGetPrices = () => dispatch => fetchAll().then((res) => {
  console.log('res', res);
  //...
});

在此處輸入圖片說明

Promise.all接受的陣列 Promises ,不Promises在參數列表中彼此之后列出。 改成:

const fetchAll = () => Promise.all([
  fetchPrices(),
  fetchSupplies()
]);

注意

.then((resultsArray) => {
  return resultsArray;
});

是多余的; 現有的Promise解析為一個結果數組,因此在其上調用.then來將另一個 Promise到其上,並接受該結果數組並解析為該數組沒有任何用處; 您可以完全忽略它。

另外,也不需要使用Promise.resolve我不知道getPricesgetSupply返回什么,但是如果您將非Promises傳遞給Promise.all ,則不會拋出任何錯誤,結果數組將僅包含這些值。 (如果返回了Promise.all ,則Promise.all將在所有此類Promise.all都解決后解決。)因此,您可以執行以下操作:

const fetchAll = () => Promise.all([
  getPrices(),
  getSupply()
]);

(當然,如果getPricesgetSupply返回非Promises,那么首先就不需要Promise.all了)

暫無
暫無

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

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