了解快速数据流和回拨

时间:2016-01-13 04:43:15

标签: node.js express

我有一个名为weather.js的文件,看起来像这样

var request = require('request');
var exports = module.exports = {};

exports.getWeather = function (cb){
    request('https://api.forecast.io/forecast/apiKey/43.0796,-89.3758', function (error, response, body) {
      if (!error && response.statusCode == 200) {
       console.log(error);
      }
      else if(!error && response.statusCode == 200) {
        console.log("forcast io response received");
        return body;
      }
    });
};

和快递路线档案:

 var express = require('express');
 var router = express.Router();
 var weather = require("../models/weather.js")


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

 module.exports = router;

我知道我的getWeather()函数有效,因为如果我在console.log(body)中打印JSON字符串,但它不会在我的浏览器中呈现。我真正理解的是异步模式是如何工作的。我认为没有打印JSON,因为在激活/完成函数之前渲染了网页。一旦返回数据,如何使用回调来从api调用中呈现数据?

2 个答案:

答案 0 :(得分:1)

您无法在此代码中执行return body

else if(!error && response.statusCode == 200) {
        console.log("forcast io response received");
        return body;
      }

如果您使用Promise,则可以编写如下代码:

'use strict';

var exports = module.exports = {};

exports.getWeather = function() {
    return Promise(function(resolve, reject) {
        request('https://api.forecast.io/forecast/apiKey/43.0796,-89.3758', function (error, res, body) {
            if (!error && response.statusCode == 200) {
                reject(error);
            } else {
                console.log("forcast io response received");
                resolve(body);
            }
        }
    });
}



var express = require('express');
var router = express.Router();
var weather = require("../models/weather.js")


 /* GET home page. */
 router.get('/', function(req, res) {
    weather
        .getWeather()
        .then(function(body){
            res.render('index', { weather: body });
        })
        .catch(function(error) {
            res.end(error);
        });
 });

 module.exports = router;

答案 1 :(得分:-1)

var request = require('request');
var exports = module.exports = {};

exports.getWeather = function (cb){
     request('https://api.forecast.io/forecast/apiKey/43.0796,-89.3758', function (error, response, body) {
         if (error) {
               console.log("Error");return;
          }
          else if(!error && response.statusCode == 200) {
            cb(body);
          }
     });
};

var express = require('express');
var router = express.Router();
var weather = require("../models/weather.js")
/* GET home page. */
 router.get('/', function(req, res) {
    weather.getWeather(function(body){
            res.render('index', { weather: body });
        })
 });

module.exports = router;