wintercounter
wintercounter

Reputation: 7468

Babel async/await only returning the promise

My issue is that the following code example will only return the Promise object and async/await doesn't work at all.

import 'babel-polyfill';

function doAsync() {
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            resolve('result')
        }, 2000)
    })
}

async function doStuff() {
    try {
        return await doAsync()
    } catch (err) {
        console.err(err);
    }
};

doStuff() // Returns the promise object
console.log('log') // Runs before timeout

Babel config

{
    presets: ["es2015"],
    plugins: [
      "transform-class-properties",
      "syntax-decorators",
      "transform-decorators-legacy",
      "syntax-async-functions",
      "transform-regenerator"
    ]
}

Upvotes: 0

Views: 990

Answers (1)

Marius Schulz
Marius Schulz

Reputation: 16440

doStuff is an asynchronous function, which returns a promise. You're not waiting for the promise to be fulfilled or rejected, but instead, you're logging to the console right away. The behavior you're observing is correct. If you want to log to the console only when the promise is fulfilled, chain a then call to the promise returned from doStuff.

Upvotes: 1

Related Questions