所以我有 2 个 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);
//...
});
最佳答案
Promise.all
接受一个 array 的 Promises
,而不是在参数列表中一个接一个地列出的 Promises
.更改为:
const fetchAll = () => Promise.all([
fetchPrices(),
fetchSupplies()
]);
注意
.then((resultsArray) => {
return resultsArray;
});
是多余的;现有的 Promise
解析为结果数组,因此调用 .then
将 另一个 Promise
链接到它上面获取该结果数组并解析为该数组没有做任何有用的事情;您可以完全不使用它。
另外,不需要使用 Promise.resolve
- 我不知道 getPrices
和 getSupply
返回什么,但是如果你通过将非 Promises 放入 Promise.all
中,不会抛出任何错误,结果数组将只包含这些值。 (如果返回 Promise,那么 Promise.all
将在所有此类 Promise 都已解决时解决。)因此,您可以这样做:
const fetchAll = () => Promise.all([
getPrices(),
getSupply()
]);
(当然,如果 getPrices
和 getSupply
都返回非 Promises,那么首先就不需要 Promise.all
)
关于javascript - Promise.all 错误 : Uncaught (in promise) TypeError: #<Promise> is not iterable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52940621/