[英]How to make 'http requests' synchronous in Node js
我正在尝试执行3个“ http请求”。 问题是,由于异步模式的性质,它无法按顺序执行。 所有请求均针对内部api。 这是示例代码:-
setInterval(function () {
// First request
request({}, function (error, response, body) {
// Second request
request({}, function (error, response, body) {
// Third request
request({}, function (error, response, body) {
})
})
})
},1000);
我想要达到的目的是基于一个条件( First request
)获取数据,更新数据( Second request
)并发送短信和电子邮件( Third request
)。 由于异步的性质,代码被重复很多次。 我正在使用setInterval,因此代码将始终每秒运行一次
您可以使用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);
}
});
});
}
因此,基本上,只需将您的异步函数包装在return new Promise
,以通过fulfill
或reject
来返回就绪数据。 在function main()
,您可以看到如何轻松定义此订单的顺序。
标题答案:您不能使它们同步。 但是您可以对它们进行排序。
您可能应该将setInterval
替换为setTimeout
,然后在第三个请求完成后再发出另一个setTimeout
。 否则, setInterval
将导致在第三个请求有机会完成之前重新发出第一个请求。 这可能是问题所在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.