I have lost hours trying to debug asynchronous code with Promises, where you find yourself in a system loop and totally lost from the actual callstack.
Long story short I have been using wrong the async/await and have been getting back a Promise instead of a result!
Let me explain it in short. If you run code like this:
var prom = new Promise(function(resolve, reject){
resolve('test');
});
var ret = await prom;
return ret;
}
var result = doSomething();
console.log(result);
It prints:
Surprise right?
Well the truth is that async functions are async and as such will always return a Promise!
return 3;
}
var ret = lolo();
console.log(ret);
Prints:
So where is the synchronous feature?
Only inside the async function!
That means right after the await statement the ret variable holds the result of the resolved Promise.
Try to imagine it like a good old threaded application.
In the main thread doSomething() returns immediatelly with a Promise not resolved yet.
In the child thread that will execute actual doSomething() await blocks and waits for the result.
So for my first example code you can do this:
var prom = new Promise(function(resolve, reject){
resolve('test');
});
var ret = await prom;
console.log(ret);//After await the Promise is resolved you can do someting with it here! Prints 'test'
return ret;
}
doSomething();
//console.log(result);
Of course you could also do the following, but then you wouldn’t need async/await at all in the first place:
var prom = new Promise(function(resolve, reject){
resolve('test');
});
var ret = await prom;
return ret;
}
doSomething().then(function(result){
console.log(result);
});
I hope the above sheds some light at async/await and helps someone from losing his mind.
Cheers!