简体   繁体   English

从回调函数内部获取变量值

[英]getting variable value from inside a callback function

I am trying to pull a variable's value from a callback function. 我正在尝试从回调函数中提取变量的值。 What am I doing wrong here? 我在这里做错了什么?

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);

in the above code, I am expecting the inner and outer storylist values to be same. 在上面的代码中,我期望内部和外部故事列表的值相同。 however the outer storyList value still comes as a null list. 但是,外部storyList值仍为空列表。

EDIT: to add to the question. 编辑:添加到问题。 I have initialized a variable storyList outside the async function. 我已经在异步函数外部初始化了一个变量storyList。 i am then taking the reply from the async function and putting it in the variable storyList. 然后,我将从异步函数中获取答复,并将其放入变量storyList中。 I was hoping to cheat my way out of the async pit of slow and brutal death that I have apparently dug for myself. 我希望从我为自己开掘的缓慢而残酷的死亡的异步陷阱中欺骗自己。 shouldnt it have worked? 它不应该起作用吗?

If getAllStoriesSet is asynchronous, then the line following its call is called before the callback is executed. 如果getAllStoriesSet是异步的,则在执行回调之前,将调用其调用之后的行。 So storyList is just like it was before the call. 所以storyList就像通话之前一样。

That's the reason why you provide a callback : you must put inside the callback the code which needs the value of reply . 这就是您提供回调的原因:您必须在回调中放入需要reply值的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM