简体   繁体   English

如何在Node JS中同步'http请求'

[英]How to make 'http requests' synchronous in Node js

I'm trying to execute 3 'http requests'. 我正在尝试执行3个“ http请求”。 The problem is, because of the nature of asynchronous mode, it doesn't execute in order. 问题是,由于异步模式的性质,它无法按顺序执行。 All requests are to internal apis. 所有请求均针对内部api。 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 ). 我想要达到的目的是基于一个条件( First request )获取数据,更新数据( Second request )并发送短信和电子邮件( 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 我正在使用setInterval,因此代码将始终每秒运行一次

You can easily sequence requests using Promises 您可以使用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 . 因此,基本上,只需将您的异步函数包装在return new Promise ,以通过fulfillreject返回就绪数据。 In function main() , you can see how the sequence for this order has been easily defined. function main() ,您可以看到如何轻松定义此订单的顺序。

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. 您可能应该将setInterval替换为setTimeout ,然后在第三个请求完成后再发出另一个setTimeout Otherwise the setInterval will cause the first request re-issued before the third request has an opportunity to complete. 否则, setInterval将导致在第三个请求有机会完成之前重新发出第一个请求。 Which is likely the issue. 这可能是问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM