繁体   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