等待异步任务完成 [英] Wait for async task to finish

查看:155
本文介绍了等待异步任务完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与一个第三方JavaScript库,其中一些功能的调用是异步交互。相反,工作异步逻辑到我的申请,我preferred写同步包装这些异步调用。我知道,我知道,这是可怕的设计,但是这是被完全重写,非常高的机会一个示范项目。我需要的东西展现团队的概念,而不是真的不必担心性能,但。

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.

这就是我想要做的:

function sync_call(input) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) {value = result;} );

    return value;
}

我试过jQuery的推迟,并承诺,但它似乎是针对异步设计模式。我想使用的同步模式在我的code。

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.

推荐答案

这行不通,因为JS VM已经从async_call移动并返回的值,而您没有设置然而。

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.

不要试图打什么是自然和内置的语言行为。你应该用一个回调技术或承诺。

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

}

另一种选择是使用一个承诺,看看 Q 。这样,您就返回一个承诺,然后附加一个监听器,然后给它,这是基本相同的回调。当承诺解决,当时将触发。

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.

这篇关于等待异步任务完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆