This question already has answers here:
How do I return the response from an asynchronous call?
                                
                                    (38个答案)
                                
                        
                4年前关闭。
            
        

我是javascript回调函数的新手。我花了很多时间尝试使它起作用,但是一直很不足。我有下面的功能。我只想调用registrationFlow()并使其进入if(found)条件,但getTrueFalse()始终返回false。将getTrueFalse()中的isRegistered设置为true(使用警报查看)。有人可以帮我指出我的问题在哪里吗?非常感谢!



function getTrueFalse() {
    var isRegistered = false;
    var registeredIds = ['APA','BBB'];
    chrome.storage.local.get("registeredId", function (result) {
        id = result["registeredId"];
        for(var i=0; i < registeredIds.length; i++) {
            if(registeredIds[i] === id) {
                isRegistered = true;
            }
        }
    });
    return isRegistered;
}

function registrationFlow() {
    chrome.storage.local.get("registered", function(result) {
        if (result["registered"]) {
            var found = getTrueFalse();
            if(found) {
                //do something
            }
        } else {
            //do something else
        }
    });
}

最佳答案

这两个功能都在访问本地存储,我不确定为什么。您的注册流程应为:

function registrationFlow() {
    var found = getTrueFalse();
    if(found) {
        //do something
    }
    else {
      //do something else
    }
}

10-06 04:50