asynchronous - 如何返回递归获取的结果?
问题描述
我有第一个异步函数
fetch("https://api.priceapi.com/v2/jobs", {
body: body,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST"
}).then((response) => {
return response.json();
}).then((data) => {
return fetchRepeat(data.job_id)
})
以及第二个递归异步函数。
function fetchRepeat(id){
fetch("https://api.priceapi.com/v2/jobs/"+ id +"/download.json?token=" + priceapisecret.secret)
.then((response) => {
return response.json()
}).then((data) =>{
if(data.status == "finished"){
var bookdata = {
title: data.results[0].content.name,
price: data.results[0].content.price
}
return bookdata;
}
else{
fetchRepeat(id)
}
})
}
我希望能够在第一个异步函数中访问 bookdata。我怎么做?
解决方案
为了谈论回报fetchRepeat
,您需要回报承诺。结果并没有如此返回undefined
。最后一个then
也没有返回递归的值,因此也解析为undefined
.
这是一个工作版本:
function fetchRepeat(id) {
// return the promise
return fetch(`https://api.priceapi.com/v2/jobs/${id}/download.json?token=${priceapisecret.secret}`)
.then(response => response.json())
.then(({ status, results: [{ content: { name: title, price } }] = [{ content: {} }] }) =>
(status === 'finished' ? { title, price } : fetchRepeat(id))); // return result of recursion
}
现在我让 ESLint 处理格式,因为我使用 airbnb,它更喜欢解构。最后一个错误then
很明显,因为 ELSint 抱怨返回一致。我强烈建议您使用 linter 和 IDE 来强制编码风格,以减少代码中的错误并使其他人更容易阅读。
推荐阅读
- javascript - 如何对 JavaScript 数组的值应用条件格式?
- html - 熊猫分析“重复行”部分未显示在 HTML 报告中
- c++ - unique_ptr 在自己的函数中分配给 nullptr
- python - 如何将数据框转换为列表(重置索引的问题)
- tensorflow - Inceptionv3 分类错误
- ios - 如何在情节提要中嵌入和对齐?
- javascript - 从 Coindesk API 获取 [Object] 而不是 JavaScript 对象
- firebase - Flutter Firebase onAuthStateChanged
- typescript - AWS cdk typescript 显示错误构造范围
- firebase - stream.listen((列表
documentList) 返回 DocumentSnapshot.Flutter [Firebase] 的实例