簡體   English   中英

Node.js等待請求完成

[英]Node.js wait until request is done

我正在嘗試制作一個簡單的應用程序,該應用程序從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
        });
    });
});

首先說明:您仍然必須處理請求調用中的錯誤(作為注釋添加)。

第二點:您可能希望采用基於Promises的方法來避免回調地獄。 請求有一個非常好的基於promise的包裝器,方便地稱為請求-承諾

這是諾言的好用例。 有很多庫,例如,您可以使用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
      });
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM