Y
Y
yarikus2014-12-18 12:19:33
JavaScript
yarikus, 2014-12-18 12:19:33

How to get response from asynchronous function?

function AppCreate(data) {
  window.WebViewJavascriptBridge.callHandler('create', data, function(response) {
    return response
  })
}

Actually, how to get a response by calling AppCreate ()?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
Boris Benkovsky, 2014-12-18
@yarikus

Well, the best thing is to use callback.

function AppCreate(data, callback) {
  window.WebViewJavascriptBridge.callHandler('create', data, function(response) {
    callback(response);
    return response;
  })
}
AppCreate(data, function(response){
  // здесь что-то делать с response
});

But this is how Callback Hall will start soon, so we came up with such a cute lib like Q (provises)
https://github.com/kriskowal/q
UPD:
function AppCreate(data) {
     var deferred = Q.defer();
      window.WebViewJavascriptBridge.callHandler('create', data, function(response) {
           deferred.resolve(data);
     });
    return response;
}

AppCreate(data).then(function(response){
  // здесь что-то делать с response
});

The difference is that your request does not know anything about how its result will be processed. It only promises to return data, and returns it. No callbacks need to be passed inside the request

S
Sergey Melnikov, 2014-12-18
@mlnkv

If the function is asynchronous, then you won’t be able to get the value except through callbacks, and promises are also a kind of callbacks, only implemented in a more convenient way

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question