nodejs 3a good way to write multiple api calls in serial

Solutions on MaxInterview for nodejs 3a good way to write multiple api calls in serial by the best coders in the world

showing results for - "nodejs 3a good way to write multiple api calls in serial"
Isabel
29 Jun 2020
1  var request = require('request');
2
3  request('http://www.test.com/api1', function (error, response, body) {
4    if (!error && response.statusCode == 200) {
5
6      request('http://www.test.com/api1', function (error, response, body) {
7        if (!error && response.statusCode == 200) {
8
9          request('http://www.test.com/api1', function (error, response, body) {
10            if (!error && response.statusCode == 200) {
11
12              //And so on...
13
14            }
15          })
16
17        }
18      })
19
20    }
21  })
22
23
24//2 Next Solution
25Depending on which version of node you are using, promises should be native...
26
27https://nodejs.org/en/blog/release/v4.0.0/
28
29https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
30
31var request = require('request');
32
33getRequest('http://www.test.com/api1').then(function (body1) {
34    // do something with body1
35    return getRequest('http://www.test.com/api2');
36}).then(function (body2) {
37    // do something with body2
38    return getRequest('http://www.test.com/api3');
39}).then(function (body3) {
40    // do something with body3
41    //And so on...
42});
43
44function getRequest(url) {
45    return new Promise(function (success, failure) {
46        request(url, function (error, response, body) {
47            if (!error && response.statusCode == 200) {
48                success(body);
49            } else {
50                failure(error);
51            }
52        });
53    });
54}