簡體   English   中英

node.js 中的鏈異步函數

[英]chain async functions in node.js

我有一個異步函數,它將my_url作為參數並在每次運行時更新其值:

function getUser(my_url) {
 var options = {url: my_url};
 request(options, function (body){
    my_url = body.url;
 });
}

我想無限次調用這個函數。 例如:getUser("a") 返回 "b",getUser("b") 返回 "c" 等等。 這里的最佳做法是什么? 我試過讓 getUser() 返回一個以my_url作為值的promise ,但我不知道如何重復調用它。

您可以嘗試這樣的操作(我稍微更改了 URL 創建以使用示例 URL 演示流程):

'use strict';

const request = require('request');

function delay(ms) {
  return new Promise((resolve) => { setTimeout(resolve, ms); });
}

function promisifiedRequest(url) {
  return new Promise((resolve, reject) => {
    request({ url }, (err, res, body) => {
      if (err) reject(err);
      else resolve(body);
    });
  });
}

(async function main() {
  try {
    let url = 'https://example.com';

    while (url !== null) {
      const body = await promisifiedRequest(url);
      url = `https://example.com?q=${
        encodeURIComponent(body.slice(0, Math.floor(Math.random() * 50)))
      }`;
      console.log(url);
      await delay(1000);
    }
  } catch (err) {
    console.error(err);
  }
})();
function getUser(my_url) {
      var options = {url: my_url};

      if(my_url == "some stop condition") return ;

      request(options, function (body){
         my_url = body.url;
      }).then( response => {
           getUser(response);
      });
  }

我不確定這是否是您要查找的內容,但這里有一個使用遞歸和request-promise的示例:

const rp = require('request-promise')

const url = "https://google.com"
var options = {
    uri: url
}

var count = 0

function chain(options, count) {
    const newURL = `${url}/?count=${count}`
    console.log(`Requesting ${newURL}`)
    rp(options).then(function(body) {
        console.log(`Success, body was ${body.length} bytes`)
        count = count + 1;
        if ( count < 20 ) {
            options = {
                uri: newURL
            }
            // recursion

            chain(options, count)
        }
    }).catch(function (err) {
        console.log(`An error occurred: ${err}`)
    })
}

chain(options, count)

當我運行這里的輸出時:

Requesting https://google.com/?count=0
Success, body was 45855 bytes
Requesting https://google.com/?count=1
Success, body was 45861 bytes
Requesting https://google.com/?count=2
Success, body was 45864 bytes
Requesting https://google.com/?count=3
Success, body was 45875 bytes
Requesting https://google.com/?count=4
Success, body was 45859 bytes
Requesting https://google.com/?count=5
Success, body was 45851 bytes
Requesting https://google.com/?count=6
Success, body was 45882 bytes
Requesting https://google.com/?count=7
Success, body was 45843 bytes
Requesting https://google.com/?count=8
Success, body was 45892 bytes
Requesting https://google.com/?count=9
Requesting https://google.com/?count=9
Success, body was 45835 bytes
Requesting https://google.com/?count=10
Success, body was 45885 bytes
Requesting https://google.com/?count=11
Success, body was 45865 bytes
Requesting https://google.com/?count=12
Success, body was 45851 bytes
Requesting https://google.com/?count=13
Success, body was 45859 bytes
Requesting https://google.com/?count=14
Success, body was 45905 bytes
Requesting https://google.com/?count=15
Success, body was 45848 bytes
Requesting https://google.com/?count=16
Success, body was 45896 bytes
Requesting https://google.com/?count=17
Success, body was 45879 bytes
Requesting https://google.com/?count=18
Success, body was 45877 bytes
Requesting https://google.com/?count=19
Success, body was 45844 bytes

如果您的服務器行為如此,您可以輕松地解析出響應中的下一個 URL then() 我放入計數以防止無限遞歸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM