How to make 'http requests' synchronous in Node js

心不动则不痛 提交于 2019-12-05 09:06:45

问题


I'm trying to execute 3 'http requests'. The problem is, because of the nature of asynchronous mode, it doesn't execute in order. All requests are to internal apis. Here's the sample code :-

setInterval(function () {
  // First request
  request({}, function (error, response, body) {
   // Second request
   request({}, function (error, response, body) {
    // Third request
    request({}, function (error, response, body) {
    })
   })
  })
},1000);

What i'm trying to achieve is get data based on one condition (First request), update data (Second request) and send sms and emails (Third request). Because of the asynchronous nature, code is getting repeated many times. I'm using setInterval so the code will always run every second


回答1:


You can easily sequence requests using Promises

// Load Dependencies: 
var Promise = require('promise');
var request = require('request');

// Begin Execution:
main();

function main() {
  getData()                //Executes 1st
   .then(updateData)       //Whatever is 'fulfilled' in the previous method, gets passed to this function updateData
   .then(sendNotification) //Whatever is fulfilled in the previoud method, gets passed to this function sendNotification.
   .catch(function(err) {
     console.log('If reject is called, this will catch it - ' +err);
   });
}

// Request #1:
function getData() {
  return new Promise(function(fulfill, reject) {
    request({}, function(err, res, body) {
      if (err) {
        reject('Error making request - ' +err);
      } else if (res.statusCode !== 200) {
        reject('Invalid API response - ' +body);
      } else {
        fulfill(body);
      }
    });
  });
}

// Request #2:
function updateData(data) {
  return new Promise(function(fulfill, reject) {
    request({}, function(err, res, body) {
      if (err) {
        reject('Error making request - ' +err);
      } else if (res.statusCode !== 200) {
        reject('Invalid API response - ' +body);
      } else {
        fulfill(body);
      }
    });
  });
}


// Request #3
function sendNotification(phoneNumber, email) {
  return new Promise(function(fulfill, reject) {
    request({}, function(err, res, body) {
      if (err) {
        reject('Error making request - ' +err);
      } else if (res.statusCode !== 200) {
        reject('Invalid API response - ' +body);
      } else {
        fulfill(body);
      }
    });
  });
}

So basically just wrap your async functions with return new Promise, to return the ready data via fulfill or reject. In function main(), you can see how the sequence for this order has been easily defined.




回答2:


Answer to title: You can't make them synchronous. But you can sequence them.

You likely should replace the setInterval with a setTimeout and then issue another setTimeout after the third request completes. Otherwise the setInterval will cause the first request re-issued before the third request has an opportunity to complete. Which is likely the issue.



来源:https://stackoverflow.com/questions/37085510/how-to-make-http-requests-synchronous-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!