Node.jsvariables在函数外部使用

我试图让我可以将我的趋势variables从其函数传递给我的帕格模板的渲染器,我似乎无法做到这一点。

var express = require('express'); var router = express.Router(); var googleTrends = require('google-trends-api'); var auth = require('http-auth'); var ustrends; var uktrends; const Console = require('console').Console; var basic = auth.basic({ realm: "Web." }, function (username, password, callback) { // Custom authentication method. callback(username === "user" && password === "pass"); } ); var find = ','; var regex = new RegExp(find, 'g'); googleTrends.hotTrends('US').then(function(trends){ ustrends = trends }); googleTrends.hotTrends('EU').then(function(trends1) { uktrends = trends1 }); console.log(ustrends); /* GET home page. */ router.get('/', auth.connect(basic), function(req, res, next) { res.render('index', {trends: ustrends.toString().replace(regex, ", "), trends1: uktrends.toString().replace(regex, ", "), title: 'Trends in the US & U.K'}); }); module.exports = router; 

正如你所看到的,我试图把“ustrends”和“uktrends”variables传递给渲染器。 任何帮助表示赞赏。

请记住, hotTrends 将返回一个承诺 ,因为它从Google的API中获得结果。 由于渲染器在ustrendsuktrends被设置为值的callback之外,因此不能保证这些值将在渲染器被调用之前设置。

你可以使用几个嵌套的callback函数,但是这会导致一些代码向右移动很远。 我build议使用asynchronous库,它有一个叫做series的函数,它允许你传递1)一个要执行的函数数组,2)一个函数完成后执行的callback函数,如果有错误一个是function的结果作为论点。 在下面的代码片段中,趋势API返callback用渲染器之前的结果:

 async.series([ function(cb) { googleTrends.hotTrends('US').then(function(trends){ ustrends = trends; cb(); }) }, function(cb) { googleTrends.hotTrends('EU').then(function(trends1) { uktrends = trends1; cb(); }); } ], function(err, results) { /* handle errors, do rendering stuff */ })