gpt4 book ai didi

javascript - Node.js 等待请求完成

转载 作者:行者123 更新时间:2023-11-28 18:42:08 25 4
gpt4 key购买 nike

我正在尝试制作一个简单的应用程序,从 API 请求一些数据。我正在使用 Express 构建它,并且我有以下代码来执行请求:

module.exports = {
getPrevMatches: function(){
request({
uri: 'http://worldcup.sfg.io/matches',
json: true
}, this.process);
},
process: function(error, response, body){
if(response.statusCode === 200){
return body;
}
}
}

以及我的快速脚本中的以下内容:

app.get('/previous', function (req, res){
var prevMatches = worldcup.getPrevMatches();

console.log(prevMatches);

res.render('prev.html', {
prevMatches: prevMatches
});
});

prevMatches 此时始终未定义。我认为请求包会等到请求完成,然后继续执行我的代码。难道不是这样吗?

谢谢。

最佳答案

使用基于回调的方法(如评论中所述):

function getPrevMatches(cb) {
request({
uri: 'http://worldcup.sfg.io/matches',
json: true
}, function(error, response, body){
if (response.statusCode === 200){
cb(body);
}
// Do error handling here!
});
}

module.exports = {
getPrevMatches: getPrevMatches
}

如您所见,无需导出流程函数。调用代码现在变为:

app.get('/previous', function(req, res){
worldcup.getPrevMatches(function(prevMatches) {
console.log(prevMatches);

res.render('prev.html', {
prevMatches: prevMatches
});
});
});

第一句话:您仍然需要处理请求调用中的错误(作为注释添加)。

第二点评论:您可能希望采用基于 Promise 的方法来避免回调 hell 。 Request 有一个非常好的基于 promise 的包装器,可以方便地调用 request-promise

关于javascript - Node.js 等待请求完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35968919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com