簡體   English   中英

從回調函數內部獲取變量值

[英]getting variable value from inside a callback function

我正在嘗試從回調函數中提取變量的值。 我在這里做錯了什么?

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

在上面的代碼中,我期望內部和外部故事列表的值相同。 但是,外部storyList值仍為空列表。

編輯:添加到問題。 我已經在異步函數外部初始化了一個變量storyList。 然后,我將從異步函數中獲取答復,並將其放入變量storyList中。 我希望從我為自己開掘的緩慢而殘酷的死亡的異步陷阱中欺騙自己。 它不應該起作用嗎?

如果getAllStoriesSet是異步的,則在執行回調之前,將調用其調用之后的行。 所以storyList就像通話之前一樣。

這就是您提供回調的原因:您必須在回調中放入需要reply值的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM