重用异步回调中的值

时间:2017-05-15 09:21:13

标签: javascript node.js express asynchronous

所以我在Node.js和express中构建一个应用程序,我有一个路由器和API模块,我从中发出HTTP请求。我正在努力绕过回调之间的传递值。

看起来像这样:

路由器:

var dataAPI = require('../API/getData');
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) { 
        dataAPI.getData(function(res, data){
                res.render('index', {data: data});
        });
});

module.exports = router;

getAPI文件具有以下功能:

var request = require('request');
var config = require('../config/config');

getData = function(callback){
    request({
        headers: {
            'Content-Type' : 'application/json',
            'Authorization' : config.authorization.token
        },
        uri: config.url.get_portfolio,
        method: 'GET',
        rejectUnauthorized: false,
    }, function(err, res, body){
        if (err || body == undefined ){
            console.log("Error in first callback.");
            throw err;
        } 
        console.log("HTTP: ", res.statusCode, " GOT DATA: ", body);
    });
}

我想在这里完成的是

res.render('index', {data }) 

并使用getData函数中的请求数据。这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您没有在getData函数发出的请求中使用回调,并且回调参数不正确 试着这样做:

var dataAPI = require('../API/getData.js')
var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) { 
        dataAPI.getData(function(err,data){
                if(err) throw err;
                res.render('index', {data: data});
        });
});

// getData.js文件

var request = require('request');
var config = require('../config/config');

exports.getData = function(callback){
    request({
        headers: {
            'Content-Type' : 'application/json',
            'Authorization' : config.authorization.token
        },
        uri: config.url.get_portfolio,
        method: 'GET',
        rejectUnauthorized: false,
    }, function(err, res, body){
        if (err || body == undefined ){
            console.log("Error in first callback")
            callback(new Error("Error in first callback."),null) <----------
        }else{
            console.log("HTTP: ", res.statusCode, " GOT DATA: ", body);
            callback(null,body) <--------------
        }
    });
}