Promise.all 错误: Uncaught (in promise) TypeError: #<Promise> 不可迭代

3

我需要调用两个API,并等待两个响应都返回后再分派我的操作。

我正在使用Promise.all,但是遇到以下错误:

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

1个回答

3

Promise.all接受一个数组作为参数,而不是在参数列表中一个接一个地列出Promises。更改为:

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

Note that

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

这里的.then方法是多余的;现有的Promise已经解决为结果数组,所以在其上调用.then方法链接另一个Promise,并将结果数组传递给它并将其解决为该数组不会产生任何有用的效果;您可以完全省略它。

另外,没有必要使用Promise.resolve - 我不知道getPricesgetSupply返回什么,但如果您将非Promise对象传递给Promise.all,则不会引发错误,生成的数组将包括这些值。 (如果返回的是Promise,则Promise.all将在所有这样的Promise都已解决时解决。)因此,您可以执行以下操作:

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

当然,如果getPricesgetSupply都返回非Promise对象,则首先不需要使用Promise.all

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接