Skip to content

Babel doesn't rewrite Promise for asyncToGenerator #5531

@alextes

Description

@alextes

Problem

I tried going through the related Babel code, but Babel is complicated 😅. Luckily the problem is simple: Babel's async-to-generator transform doesn't rewrite the Promise name. So if I overwrite Promise by importing bluebird for example, that's what I'll get back from awaiting something. Node gives me an ES6 Promise instead (now that it supports async/await)! I understand from @ljharb that according to the spec, Node's way is the correct one here. Async functions should return ES6 Promises.

Code Example

.babelrc

{
  "plugins": ["transform-async-to-generator"]
}

promise.test.js

const tap = require('tap');
const Promise = require('bluebird');

async function delay() {
    await Promise.delay(500);
}

const notABluebirdPromise = delay();
tap.equal(typeof notABluebirdPromise.delay, 'undefined');

This test passes using Node v7. The same test fails using babel-node.

Here's the compiled code for reference.
babeled-promise.test.js

let delay = (() => {
    var _ref = _asyncToGenerator(function* () {
        yield Promise.delay(500);
    });

    return function delay() {
        return _ref.apply(this, arguments);
    };
})();

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

const tap = require('tap');
const Promise = require('bluebird');

const notABluebirdPromise = delay();
tap.equal(typeof notABluebirdPromise.delay, 'undefined');

Context

I personally ran into this helping someone and expecting their code to fail because they made the assumption the awaited promise would be a bluebird one. Instead, it passed, as it was transformed using the async-to-generator. It's hard for me to estimate how often this could be a nasty problem. Being caught off guard by this rather than learning Node does async/await differently requires some asymmetry of environments. Hopefully, the issue is welcome.

Your Environment

software version
Babel 6.23.0 (babel-core 6.23.1)
node 7.7.4
npm 4.4.4
Operating System darwin

Metadata

Metadata

Assignees

No one assigned

    Labels

    Has PRoutdatedA closed issue/PR that is archived due to age. Recommended to make a new issue

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions