Leon Gaban
Leon Gaban

Reputation: 39044

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);
  //...
});

enter image description here

Upvotes: 3

Views: 4868

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371233

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)

Upvotes: 3

Related Questions