【问题标题】:How to recursively call a single fetch request in a chain of fetch requsts如何在获取请求链中递归调用单个获取请求
【发布时间】:2020-08-16 10:09:35
【问题描述】:

我正在制作一个使用 node-fetch 模块的 node.js 和 express 网络应用程序。下面是我的代码关键部分的sn-p

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 接收面积作为参数并输出电力。它是递归的,因为功率输出必须低于某个阈值。如果低于该阈值,则返回该值,否则使用更改的输入参数再次调用 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.js express asynchronous recursion fetch


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-29
      • 2019-08-10
      • 2021-03-29
      • 2020-10-26
      • 1970-01-01
      • 2021-09-24
      • 2014-02-05
      • 1970-01-01
      相关资源
      最近更新 更多