babel / kneden

Transpile ES2017 async/await to vanilla ES6 Promise chains: a Babel plugin
ISC License
514 stars 41 forks source link

Variables goes out of scope prematurely #123

Open TheGrandmother opened 6 years ago

TheGrandmother commented 6 years ago

I had this code:

1 const cid = await getCid(slackUsername)
2 await replyFn(`Creating time report for ${year} ${month} and ${cid}`)
3 const resp = await request.post(config.apiUrl + `/create-time-report/${cid}/${year}/${month}`)

And I got this strange error that cid was undefined on line 3, but it was defined properly on line 2. After a lot of crying i looked into the generated code and i found that it had been transpiled to:

1  return Promise.resolve().then(function () {
2     return getCid(slackUsername);
3   }).then(function (_resp) {
4    const cid = _resp;
5    return replyFn(`Creating time report for ${year} ${month} and ${cid}`);
6  }).then(function () {
7    return request.post(config.apiUrl + `/create-time-report/${cid}/${year}/${month}`)
8  })

As is clear from the transpiled code cid goes out of scope prematurely.

I am running version 1.0.5 of async-to-promises.

loganfsmyth commented 6 years ago

Thanks for filing. Beware that this module is essentially unmaintained currently. Happy to leave this open, but it probably won't get fixed.

You may want to take a look at https://www.npmjs.com/package/fast-async

TheGrandmother commented 6 years ago

@loganfsmyth Yhea I realized that, this has been another exercise in "don't just pull random npm packages" :p

Thanks for the tip! I siwtched to async-to-generators but fast-async seems much better :)

mikirejf commented 6 years ago

@TheGrandmother You first need to transpile your code to ES5, if you want the plugin to work as expected. That way, all the variables get hoisted to the top of the scope.

  var cid, resp;
  return Promise.resolve().then(function () {
    return getCid(slackUsername);
  }).then(function (_resp) {
    cid = _resp;
    return replyFn(`Creating time report for ${year} ${month} and ${cid}`);
  }).then(function () {
    return request.post(config.apiUrl + `/create-time-report/${cid}/${year}/${month}`);
  }).then(function (_resp) {
    resp = _resp;
  });
shellscape commented 6 years ago

Getting this as well. Transpiling to ES5 for this to work is a major bummer, as my target is Node 6.