jQuery 等待异步任务完成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18729761/
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
Wait for async task to finish
提问by Code Different
I'm interacting with a third-party JavaScript library where some function calls are asynchronous. Instead of working the asynchronous logic into my application, I preferred to write synchronous wrappers to those async calls. I know, I know, it's terrible design, but this is a demo project with very high chance of being rewritten entirely. I need something to show the team the concept, not really having to worry performance, yet.
我正在与第三方 JavaScript 库进行交互,其中一些函数调用是异步的。我没有在我的应用程序中使用异步逻辑,而是更喜欢为这些异步调用编写同步包装器。我知道,我知道,这是一个糟糕的设计,但这是一个非常有可能被完全重写的演示项目。我需要一些东西来向团队展示这个概念,而不必担心表现。
Here's what I wanna do:
这是我想要做的:
function sync_call(input) {
var value;
// Assume the async call always succeed
async_call(input, function(result) {value = result;} );
return value;
}
I tried the jQuery's deferred and promise but it seems to be aiming at the async design pattern. I want to use the synchronous pattern in my code.
我尝试了 jQuery 的 deferred 和 promise,但它似乎是针对异步设计模式的。我想在我的代码中使用同步模式。
采纳答案by bitoiu
This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.
这永远不会奏效,因为 JS VM 已从该 async_call 转移并返回了您尚未设置的值。
Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.
不要试图与语言行为的自然和内在行为作斗争。您应该使用回调技术或承诺。
function f(input, callback) {
var value;
// Assume the async call always succeed
async_call(input, function(result) { callback(result) };
}
The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.
另一种选择是使用承诺,看看Q。这样你返回一个promise,然后你给它附加一个then监听器,这与回调基本相同。当 promise 解决时, then 将触发。
回答by jbiz
How about calling a function from within your callback instead of returning a value in sync_call()?
如何从回调中调用函数而不是在 sync_call() 中返回值?
function sync_call(input) {
var value;
// Assume the async call always succeed
async_call(input, function(result) {
value = result;
use_value(value);
} );
}