节点.js等待请求完成

Node.js wait until request is done

本文关键字:请求 等待 js 节点      更新时间:2023-09-26

我正在尝试制作一个简单的应用程序,从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
    });
});

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

谢谢。

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

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
        });
    });
});

第一个备注:您仍然需要处理来自请求调用的错误(作为注释添加)。

第二点:你可能想要一个基于承诺的方法,以避免回调地狱。请求有一个非常好的基于承诺的包装器,称为方便的请求-承诺

这是承诺的一个很好的用例。有很多库,例如您可以使用 https://www.npmjs.com/package/request-promise。

var rp = require('request-promise');
module.exports = {
    getPrevMatches: function(){
        return rp({
            uri: 'http://worldcup.sfg.io/matches',
            json: true
        });
    }
}

我不确定this.process在这种情况下是否有效

app.get('/previous', function (req, res){
    var prevMatches = worldcup.getPrevMatches();
    prevMatches.then(function (data) {
      console.log(data);
      res.render('prev.html', {
          prevMatches: data
      });
    })
    prevMatches.catch(function (e) {
      res.status(500, {
          error: e
      });
    });
});