简体   繁体   中英

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

So I have 2 APIs I need to hit, and wait on both responses to come back before I dispatch my action.

I'm using Promise.all however running into the following error:

index.js:51 Uncaught (in promise) TypeError: # is not iterable at 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 accepts an array of Promises , not Promises listed after one another in the parameter list. Change to:

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

Note that

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

is superfluous; the existing Promise resolves to an array of results, so calling .then on it to chain another Promise onto it that takes that array of results and resolves to that array doesn't do anything useful; you can leave it off entirely.

Also, there's no need to use Promise.resolve - I don't know what getPrices and getSupply return, but if you pass non-Promises into Promise.all , no error will be thrown, the resulting array will simply include those values. (If Promises are returned, then the Promise.all will resolve when all such Promises have resolved.) So, you could do:

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

(of course, if both getPrices and getSupply return non-Promises, then there's no need for Promise.all in the first place)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM