javascript 将回调数据分配给变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23574256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
assign callback data to a variable
提问by MrPilot
I've been trying to figure out how to set the value from a callback to a variable so that I can call the variable and access the data rather than having to place all my code inside the callback function. I posted two examples one which works, and the second which does work and returns undefined. How can I make it so that the second example works?
我一直试图弄清楚如何将回调中的值设置为变量,以便我可以调用该变量并访问数据,而不必将所有代码都放在回调函数中。我发布了两个示例,一个有效,第二个有效并返回未定义。我怎样才能使第二个例子有效?
Here is where I get my data.
这是我获取数据的地方。
var chromeApi = {
msg: function (callbacks) {
chrome.runtime.sendMessage({type: "settings"}, callbacks);
}
};
When I access the data from chromeApi
this way it works fine.
当我以chromeApi
这种方式访问数据时,它工作正常。
chromeApi.msg(function (response) {
console.log(response);
});
But I want to access it this way I get undefined. How can I make my code work to use this method?
但我想以这种方式访问它,但我没有定义。如何使我的代码工作以使用此方法?
var test = chromeApi.msg(function (response) {
return response;
});
console.log(test);
回答by sfletche
Welcome to the world of asynchronous programming. :)
欢迎来到异步编程的世界。:)
If you want to assign response
to test
, you CANdo so within the asynchronous callback:
如果你想分配response
给test
你CAN异步回调中这样做:
chromeApi.msg(function (response) {
test = response;
});
console.log(test);
BUT...because the callback is asynchronous (meaning we don't know when that assignment statement will actually execute) we won't know whether or not
但是……因为回调是异步的(意味着我们不知道该赋值语句何时实际执行)我们不知道是否
test = response;
is executed before
之前执行
console.log(test)
until run-time.
直到运行时。
My guess from the above code is that console.log(test)
will get executed before test = response
(however, that same order of execution may not happen every time as asynchronous programming exhibits non-deterministic behavior).
我对上述代码的猜测是,console.log(test)
它将在之前执行test = response
(但是,由于异步编程表现出非确定性行为,因此可能不会每次都发生相同的执行顺序)。
Depending on what you want to do with the response value will dictate whether or not it needs to be done within the callback.
根据您想对响应值做什么,将决定是否需要在回调中完成。
This is guaranteed to work
这保证有效
chromeApi.msg(function (response) {
test = response;
// do something with test
});
this is not
这不是
chromeApi.msg(function (response) {
test = response;
});
//do something with test