简体   繁体   English

Promise.all错误:未捕获(承诺)TypeError:# <Promise> 是不可迭代的

[英]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. 因此,我需要点击2个API,并在我分派动作之前等待这两个响应返回。

I'm using Promise.all however running into the following error: 我正在使用Promise.all但是Promise.all以下错误:

index.js:51 Uncaught (in promise) TypeError: # is not iterable at Function.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 accepts an array of Promises , not Promises listed after one another in the parameter list. Promise.all接受的阵列 Promises ,不Promises在参数列表中彼此之后列出。 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; 现有的Promise解析为一个结果数组,因此在其上调用.then来将另一个 Promise到其上,并接受该结果数组并解析为该数组没有任何用处; 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. 另外,也不需要使用Promise.resolve我不知道getPricesgetSupply返回什么,但是如果您将非Promises传递给Promise.all ,则不会抛出任何错误,结果数组将仅包含这些值。 (If Promises are returned, then the Promise.all will resolve when all such Promises have resolved.) So, you could do: (如果返回了Promise.all ,则Promise.all将在所有此类Promise.all都解决后解决。)因此,您可以执行以下操作:

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) (当然,如果getPricesgetSupply返回非Promises,那么首先就不需要Promise.all了)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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