How to make 'http requests' synchronous in Node js

余生颓废 提交于 2019-12-03 21:36:20

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.

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.

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