Wait for async task to finish

后端 未结 2 2119
灰色年华
灰色年华 2020-12-13 05:52

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

相关标签:
2条回答
  • 2020-12-13 06:39

    How about calling a function from within your callback instead of returning a value in sync_call()?

    function sync_call(input) {
        var value;
    
        // Assume the async call always succeed
        async_call(input, function(result) {
            value = result;
            use_value(value);
        } );
    }
    
    0 讨论(0)
  • 2020-12-13 06:46

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

    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.

    0 讨论(0)
提交回复
热议问题