我试图从回调函数中提取变量的值.我在这做错了什么?
var storyList = [];
var storyTemp ={};
// get list of all stories
db.getAllStoriesSet(function(err, reply) {
if (err) throw err;
else {
storyList = reply;
console.log("storylist inner: " + storyList);
};
});
console.log("storylist outer: " + storyList);
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我期待内部和外部故事列表值相同.但是,外部storyList值仍然作为空列表.
编辑:添加问题.我在异步函数之外初始化了一个变量storyList.然后我接受来自异步函数的回复并将其放入变量storyList中.我本来希望欺骗我的方式摆脱我显然为自己挖掘的缓慢和残酷死亡的异步坑.不应该有用吗?
如果getAllStoriesSet是异步的,则在执行回调之前调用其调用之后的行.所以,storyList就像是在调用之前.
这就是你提供回调的原因:你必须在回调中放入需要值的代码reply.
| 归档时间: |
|
| 查看次数: |
155 次 |
| 最近记录: |