首页 > 解决方案 > 如何在获取请求链中递归调用单个获取请求

问题描述

我正在制作一个使用 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() 继续不等待递归调用完成。

标签: node.jsexpressasynchronousrecursionfetch

解决方案


你只是忘记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

推荐阅读