显示多个 API 调用的结果
Displaying results of multiple API calls
我正在对后端服务器进行两次 API 调用,我正在使用以下方法向用户显示 json 中的两个响应。但是,根据控制台,警报 2 是 'undefined';警报 1 有效。我做错了什么?
app.get("/blah", function (req, res) {
var alert = 'api call for alert'
var alert2 = 'api call for alert 2'
request(alert, alert2, function (error, response, alert, alert2) {
console.log(alert);
console.log(alert2);
res.json({
Alert: alert,
Alert2: alert2
});
});
});
这是因为 request 不允许以这种方式从一次调用中异步发出多个请求。
异步实现此目的的一种方法是使用异步模块中的 async.parallel。
但是,为了简单起见,我将提供一个不需要异步模块的示例,而是以串行方式工作。
这不是最有效的方法,因为在您的示例中,第二个请求不需要先完成第一个请求。
app.get("/blah", function (req, res) {
var alert = 'api call for alert'
var alert2 = 'api call for alert 2'
request(alert, function (error, response, alert) {
console.log(alert);
request(alert2, function (error, response, alert2) {
console.log(alert2);
res.json({
Alert: alert,
Alert2: alert2
});
});
});
});
异步示例 (https://github.com/caolan/async):
app.get("/blah", function (req, res) {
var alert = 'api call for alert'
var alert2 = 'api call for alert 2'
async.parallel([
function(callback) {
request(alert, function (error, response, alert) {
if(error) {
callback(error);
} else {
callback(null, alert);
}
});
},
function(callback) {
request(alert2, function (error, response, alert2) {
if(error) {
callback(error);
} else {
callback(null, alert2);
}
});
}
], function(err, results) {
res.json({
Alert: results[0],
Alert2: results[1]
});
});
});
我正在对后端服务器进行两次 API 调用,我正在使用以下方法向用户显示 json 中的两个响应。但是,根据控制台,警报 2 是 'undefined';警报 1 有效。我做错了什么?
app.get("/blah", function (req, res) {
var alert = 'api call for alert'
var alert2 = 'api call for alert 2'
request(alert, alert2, function (error, response, alert, alert2) {
console.log(alert);
console.log(alert2);
res.json({
Alert: alert,
Alert2: alert2
});
});
});
这是因为 request 不允许以这种方式从一次调用中异步发出多个请求。
异步实现此目的的一种方法是使用异步模块中的 async.parallel。
但是,为了简单起见,我将提供一个不需要异步模块的示例,而是以串行方式工作。
这不是最有效的方法,因为在您的示例中,第二个请求不需要先完成第一个请求。
app.get("/blah", function (req, res) {
var alert = 'api call for alert'
var alert2 = 'api call for alert 2'
request(alert, function (error, response, alert) {
console.log(alert);
request(alert2, function (error, response, alert2) {
console.log(alert2);
res.json({
Alert: alert,
Alert2: alert2
});
});
});
});
异步示例 (https://github.com/caolan/async):
app.get("/blah", function (req, res) {
var alert = 'api call for alert'
var alert2 = 'api call for alert 2'
async.parallel([
function(callback) {
request(alert, function (error, response, alert) {
if(error) {
callback(error);
} else {
callback(null, alert);
}
});
},
function(callback) {
request(alert2, function (error, response, alert2) {
if(error) {
callback(error);
} else {
callback(null, alert2);
}
});
}
], function(err, results) {
res.json({
Alert: results[0],
Alert2: results[1]
});
});
});