node.js - 如何在获取请求链中递归调用单个获取请求
问题描述
我正在制作一个使用 node-fetch 模块的 node.js 和 express web 应用程序。以下是我的代码关键部分的片段
fetchGeoLocation(geoApiKey)
.then(coordinates => {
data x = getSomeData(); //returns data needed for next fetch API call.
return fetchWithRetry(//various parameters provided by var data...);
}
.then(powerData =>{
///continue on...
}
对于某些上下文: fetchWithRetry 接收 area 作为参数并输出电力。它是递归的,因为功率输出必须低于某个阈值。如果低于此阈值,则返回该值,否则使用更改的输入参数再次调用 fetchWithRetry()。
这是我的 fetchWithRetry() 函数的重要部分:
function fetchWithRetry(params...){
return fetch(///powerData)
.then(res => res.json())
.then(powerData => {
if( //powerData isn't good){
fetchWithRetry(change params...)
}
return powerData;
TL;DR--> 以下是确切的问题:
最后一个回调,powerData,不等待 fetchWithRetry 的结果,它可能在递归调用之后。我已经验证 fetchWithRetry 可以正常工作,但是递归调用是在最后一次 .then() 调用之后进行的,因此它不会等待它。
我已经尝试使用 async/await 作为坐标和 fetchWithRetry 但最后一个 .then() 继续不等待递归调用完成。
解决方案
你只是忘记return
了递归fetchWithRetry
。这是一个例子:
const timeOutPromise = (i)=>{
return new Promise((res)=>{
setTimeout(() => {
res(i)
}, 100);
})
}
function fetchWithRetry(i){
return timeOutPromise(i)
.then(d=>{
process.stdout.write(d+" ");
if(d<10){
return fetchWithRetry(d+1)
}else{
return d
}
})
}
fetchWithRetry(0).then((d)=>{
console.log("\nThe Latest Value: ",d);
console.log("done");
})
结果是:
0 1 2 3 4 5 6 7 8 9 10
The Latest Value: 10
done
推荐阅读
- asp.net-core - ModelState.IsValid() 即使在之前的 ModelState 关闭后也不会验证
- go - fabric-sdk-go.beta3 执行 LifecycleApproveCC 失败
- reactjs - 如何解决 npm 缺少脚本:构建和托管我的反应应用程序?
- amazon-s3 - 尝试将冰川深度存档恢复到 s3,但无法使用 mfa 执行此操作
- excel - 如何使用以单元格颜色为基础的if else填充单元格
- android - Android BLE 权限
- neural-network - 如何使用神经网络检测和识别文档信息?
- android - 无法使用 TabLayoutManager
- html - Display tooltip on hover in cutom toggle switch
- python - 无法在 linux 上安装 Django 框架(PopOS - 基于 Ubuntu)