我正在查询Yelp API中的一些数据。业务的Console.log在终端中工作正常,但当我在模板中调用相同的变量进行渲染时,没有任何内容显示。
result = 1L * x[a] * x[b] * x[c] * x[d] * x[e] * x[f] * x[g] * x[h]
* x[i] * x[j] * x[k] * x[l] * x[m];
答案 0 :(得分:3)
yelp.search
是异步的。您必须在回调中调用res.render
,例如:
yelp.search({location: "tempe", term: "sandwiches", category_filter: "food"}, function(error, data) {
var test = JSON.stringify(data); //Changes yelps response to JSON Objects with double quotes
test = JSON.parse(test); //JSON.parse can now parse correctly after stringify is used.
// for(var i = 0; i < 9; i++){
// console.log(test['businesses'][i]['name']);
// // console.log(test['businesses'][i]);
// }
console.log(test['businesses'][0]['name']);
first = test['businesses'][0]['name'];
res.render('helloworld', {
title: 'Hello, World',
name: first
});
});
,否则会在yelp.search
返回之前调用。
答案 1 :(得分:1)
这是异步回调。
当yelp.search
exec和回调仍然不是exec时,name
未定义。所以你的渲染{name:'undefined'}。
除了@Rodrigo Medeiros的方式,您还可以使用一些模块来解决。例如:q
,asnyc
,bluebird
等等。