📜  NodeJS:串行编写多个 API 调用的好方法 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:04:04.489000             🧑  作者: Mango

代码示例1
var request = require('request');

  request('http://www.test.com/api1', function (error, response, body) {
    if (!error && response.statusCode == 200) {

      request('http://www.test.com/api1', function (error, response, body) {
        if (!error && response.statusCode == 200) {

          request('http://www.test.com/api1', function (error, response, body) {
            if (!error && response.statusCode == 200) {

              //And so on...

            }
          })

        }
      })

    }
  })


//2 Next Solution
Depending on which version of node you are using, promises should be native...

https://nodejs.org/en/blog/release/v4.0.0/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

var request = require('request');

getRequest('http://www.test.com/api1').then(function (body1) {
    // do something with body1
    return getRequest('http://www.test.com/api2');
}).then(function (body2) {
    // do something with body2
    return getRequest('http://www.test.com/api3');
}).then(function (body3) {
    // do something with body3
    //And so on...
});

function getRequest(url) {
    return new Promise(function (success, failure) {
        request(url, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                success(body);
            } else {
                failure(error);
            }
        });
    });
}