匿名函数中的JSvariables的范围是什么?

为什么这个代码返回$ products是空的? 如果我testing$产品内的function,它显示数据…但一旦完成,我似乎无法得到的数据。

var $products = new Array(); connection.query($sql, function(err, rows, fields) { if (err) throw err; for(i=0; i< rows.length; i++) { $products[rows[i].source_identifier] = "xyz"; } }); connection.end(); console.log($products); // Shows empty. 

它不会返回空; 没有return声明。 问题是操作是asynchronous的 。 当您的console.log()调用运行时,查询尚未完成。

for循环之后,将您的console.log()调用移动到该callback函数中。 (也用var声明“i”)

使用涉及这种callback的API的全部意义在于应付操作是asynchronous的这一事实。 如果它们是同步的,那么devise这样的接口会很奇怪。