function foo(){
// doDo something
return 'wohoo';
}
let bar = foo(); // bar'bar' is 'wohoo' here
Now let's add a bit of twist, by introducing a little delay in our function, so that all lines of code are not 'finished' in sequence. Thus, it will emulate the asynchronous behavior of the function :
function foo(){
setTimeout( ()=> {
return 'wohoo';
}, 1000 )
}
let bar = foo() // bar'bar' is undefined here
So there you go,go; that delay just broke the functionality we expected! But what exactly happened ? Well, it's actually pretty logical if you look at the code. the
The function foo()
, upon execution, returns nothing (thus returned value is undefined
), but it does start a timer, which executes a function after 1s1 second to return 'wohoo'. But as you can see, the value that's assigned to bar is the immediately returned stuff from foo(), which is nothing, i.e., just undefined
.
Let's ask our function for a PROMISEpromise. Promise is really about what it means : it means that the function guarantees you to provide with any output it gets in future. soSo let's see it in action for our little problem above :
function foo(){
return new Promise( (resolve, reject) => { // I want foo() to PROMISE me something
setTimeout ( function(){
// promisePromise is RESOLVED , when the execution reaches this line of code
resolve('wohoo') // After 1 second, RESOLVE the promise with value 'wohoo'
}, 1000 )
})
}
let bar ; bar;
foo().then( res => {
bar = res;
console.log(bar) // willWill print 'wohoo'
});
Thus, the summary is - to tackle the asynchronous functions like ajax basedAjax-based calls, etc., you can use a promise to resolve
the value (which you intend to return). Thus, in short you resolve value instead of returning, in asynchronous functions.