Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to resolve promise when using async await with babel and ES6 promise

I have the following node app containing an async function, awaiting an ES6 promise.

async function test(id){
    try {
        let val = await Promise.resolve(id);
        console.log("val: " + val);
    } catch (error) {
        console.log("error: " + error);
    }
}

test(1);

Result = val: undefined

Expected result: val: 1

I use gulp-babel to compile this to ES5.

I have the following set within the gulp task:

.pipe(babel({ optional: ["es7.asyncFunctions"] }))

I am also requiring in 'babel/polyfill' after npm installing babel.

Transpiled code:

function test(id) {
var val;
return regeneratorRuntime.async(function test$(context$1$0) {
    while (1) switch (context$1$0.prev = context$1$0.next) {
        case 0:
            context$1$0.prev = 0;
            context$1$0.next = 3;
            return Promise.resolve(id);

        case 3:
            val = context$1$0.sent;

            console.log('val: ' + val);
            context$1$0.next = 10;
            break;

        case 7:
            context$1$0.prev = 7;
            context$1$0.t0 = context$1$0['catch'](0);

            console.log('error: ' + context$1$0.t0);

        case 10:
        case 'end':
            return context$1$0.stop();
    }
}, null, this, [[0, 7]]);
}

test(1);
like image 321
Daniel Billingham Avatar asked Jun 06 '15 19:06

Daniel Billingham


People also ask

Can we use promise with async await?

async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

Does await wait for promise to resolve?

The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or a JavaScript module.

Is await the same as promise resolve?

Promise creation starts the execution of asynchronous functionality. await only blocks the code execution within the async function. It only makes sure that the next line is executed when the promise resolves. So, if an asynchronous activity has already started, await will not have any effect on it.


1 Answers

You appear to be using a version of Babel prior to Babel version 5.5.0. Before this version, it was possible to have regenerator (a dependency of Babel) installed at a version less than 0.8.28, which is the first version where regenerator started supporting await Promise.resolve(value) (the code in your example).

Support was added in this commit on the regenerator side, and Babel upgraded to require at least the 0.8.28 release of regenerator with this commit.

like image 52
Mark Rousskov Avatar answered Oct 04 '22 05:10

Mark Rousskov