0

I'm stuck figuring how set a variable value (ex. response of an ajax call) using promises.

I have for instance:

something.value = getVariable('id'); // { id : 'Adam Smith' }

where

getVariable(id) { 
    return $.ajax({
    //...
}).done(function(response) {
    //... getVariable return response
}).fail(function(response) {
    //... getVariable return something_else
});
    // ...

getVariable should change from promise to ajax (or any other asynchronous) response value once done().

Daniele
  • 829
  • 1
  • 13
  • 23
  • you can't do that because promises don't make asynchronous code synchronous – Jaromanda X Aug 11 '16 at 12:39
  • Ok, so the only way is to assign value into a callback right? – Daniele Aug 11 '16 at 12:42
  • if I understand what you mean, then yes – Jaromanda X Aug 11 '16 at 12:48
  • Yes to Jaromanda X. As a side note, what your code sample does is that it stores your ajax as a `Promise` object to the 'something.value'. To continue with that pattern, do something like `getVariable('id').then( function(response) { something.value = response; });` – kyw Aug 11 '16 at 12:57
  • "change from promise to ajax"? Promises are asynchronous. – Daniel Lizik Aug 11 '16 at 12:57
  • You have to remain in the asynchronous timeline all the way when you do some asynchronous task. Whatever you need to do with the result of the asynchronous call you have to handle it within a `then` stage. Even if with promises you find this confusing you may simulate a synchronous workflow within a generator function by utilizing a coroutine approach. Hava a look at https://curiosity-driven.org/promises-and-generators – Redu Aug 11 '16 at 13:17
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Roamer-1888 Aug 12 '16 at 08:02

1 Answers1

1

You can't directly set a variable the way you're trying to do it. Because your operations are async, the only place you can reliably use the result of your async operations is inside the promise handlers such as .done() or .then(). So, setting the result into some variable and then expecting to use that variable in other code usually won't work properly. It will usually result in timing issues.

Instead, you have to learn to program with asynchronous results where you actually USE the variable inside the promise handler callback. You don't store it and then expect to use it in other code.

function getVariable(id) { 
    return $.ajax({...});
});

getVariable(...).then(function(response) {
    // process result here
    // don't just store it somewhere and expect other code to use that stored
    // value.  Instead, you use the result here and put whatever code
    // needs that value in here.
}, function(err) {
    //  handle error here
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979