【发布时间】:2021-04-26 13:26:39
【问题描述】:
我正在尝试从 API 获取数据,但结果一直未定义。我正在使用 promise.all 链接 API 调用,然后链接 promise 以对数据执行其他操作。我似乎无法将我的结果传递给 state。
这是有问题的代码:
if (gameDifficulty === "mixed") {
const result = await Promise.all([
fetchClient.getData(
getEndpoint(
`amount=${countValues[0]}&difficulty=easy&type=${questionType}`
)
),
fetchClient.getData(
getEndpoint(
`amount=${countValues[1]}&difficulty=medium&type=${questionType}`
)
),
fetchClient.getData(
getEndpoint(
`amount=${countValues[2]}&difficulty=hard&type=${questionType}`
)
),
])
.then(function (responses) {
console.log(responses);
console.log(result); //returns undefined
return Promise.all(
responses.map(function (response, idx) {
return fetchClient.processData(response, "results");
})
);
})
.then(function (data) {
console.log(data);
console.log(result); // returns undefined
return [...data[0], ...data[1], ...data[2]];
});
}
【问题讨论】:
-
您将
async/await与.then代码混合在一起,不要那样做。只需使用其中之一。还有为什么你甚至需要result在那个.then,你已经有responses这将是同一件事 - API 请求的响应 -
这是一个跟踪问题的尝试。我想看看会得到什么。其他控制台日志返回预期结果,但整个函数返回未定义。我认为这是一个异步的事情。
标签: javascript reactjs fetch undefined promise.all