【发布时间】:2019-08-11 10:42:46
【问题描述】:
我需要按顺序从三个 http 请求中获取响应。
我可以使用嵌套函数来做到这一点。我还需要使用全局范围内最后一个请求的响应,而嵌套解决方案无法做到这一点。
var request = require("request");
httpRequest1((getRequest1) => {
console.log(getRequest1);
httpRequest2((getRequest2) => {
console.log(getRequest2);
httpRequest3((getRequest3) => {
console.log(getRequest3);
});
});
});
function httpRequest1 (callback){
var options = { method: 'POST',
url: };
request(options, function (error, response, body) {
if (error) throw new Error(error);
callback (body);
});}
function httpRequest2(callback){
var options = { method: 'POST',
url: };
request(options, function (error, response, body) {
if (error) throw new Error(error);
callback(body);
});}
function httpRequest3(callback){
var options = { method: 'POST',
url: };
request(options, function (error, response, body) {
if (error) throw new Error(error);
callback(body);
});}
【问题讨论】:
-
那就是你怎么做的。如果您需要最终结果,请在回调中访问它。或者,查看 Promise。
-
我推荐使用 Promose 或 Async/Await 。避免回调,因为它可能会发生回调地狱。
-
你将如何实现 Async/Await?当我尝试使用 Async/Await 时,我得到一个未定义的响应,好像它并没有真正等待请求完成。
标签: node.js asynchronous chaining