【问题标题】:NodeJS: How to wait for the HTTP Get request is complete in For Loop?NodeJS:如何在 For Loop 中等待 HTTP Get 请求完成?
【发布时间】:2018-09-12 17:58:08
【问题描述】:

我在 NodeJS 中有一个 for 循环函数。我想等到 Http Get 请求的结果在 For Loop 中完成后再执行下一次迭代,我该如何实现呢?

for (let k=0; k<fd.length; k++) {
    url = fd[k].nct_id;

    HttpSearch({condition: url}).then(trials => {
         //Get the result first before execute the next iteration
         console.log(trials);
    });
}

【问题讨论】:

    标签: node.js


    【解决方案1】:

    你应该创建for循环async

    const main = async () => {
      for (let k = 0; k < fd.length; k++) {
        const url = fd[k].nct_id;
    
        const trials = await HttpSearch({ condition: url });
    
        console.log(trials);
      }
    };
    
    main().catch(console.error);
    

    这将导致循环在每个HttpSearch 处“暂停”。

    【讨论】:

      【解决方案2】:

      我会这样做

      let k = 0 ;
      let len = fd.length;
      for (; k > len;) { 
        let url = fd[k].nct_id;
        let subs = await HttpSearch({condition: url});
        console.log(subs);
        k++
      }
      

      或者像这样承诺

      let url;
      let promiseChain = Promise.resolve();
      for (let i = 0; i < fd.length; i++) { 
          url = fd[k].nct_id;
      
          // you need to pass the current value of `url`
          // into the chain manually, to avoid having its value
          // changed before the .then code accesses it.
      
          const makeNextPromise = (url) => () => {
      
               HttpSearch({condition: url})
                  .then((result) => {
                      // return promise here
                      return result
                  });
          }
      
          promiseChain = promiseChain.then(makeNextPromise(url))
      }
      

      【讨论】:

        【解决方案3】:

        这是使用递归,一旦上一个完成,它就会调用下一个

        var limit = fd.length;
        var counter = 0;
        
        HttpSearch({condition: fd[0].nct_id;}).then(yourCallBack);
        
        function yourCallBack(trials){
            console.log(trails);
            if(counter == limit)
                return console.log('Done')
            HttpSearch({condition: fd[counter].nct_id;}).then(yourCallBack);
            counter++;
        }
        

        【讨论】:

          猜你喜欢
          • 2021-07-30
          • 1970-01-01
          • 2018-07-19
          • 2020-03-04
          • 2017-07-30
          • 2017-07-04
          • 2020-01-14
          • 1970-01-01
          • 2017-08-08
          相关资源
          最近更新 更多