Javascript async/await explained

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:

async function doSomething(){
    var prom = new Promise(function(resolve, reject){
        resolve('test');
    });
    var ret = await prom;
    return ret;
}

var result = doSomething();
console.log(result);

It prints:

  Promise { pending }

Surprise right?

Well the truth is that async functions are async and as such will always return a Promise!

async function lolo(){
    return 3;
}

var ret = lolo();
console.log(ret);

Prints:

  Promise { 3 }

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:

async function doSomething(){
    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:

async function doSomething(){
    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!