我正在尝试执行 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);
我想要实现的是根据一个条件获取数据(第一个请求
),更新数据(第二个请求
)并发送短信和电子邮件(第三个请求
)。由于异步性质,代码会重复很多次。
我正在使用 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()
中,您可以看到如何轻松定义此订单的序列。
关于javascript - 如何在Node js中使 'http requests'同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37085510/