Tuan Anh Tran
Tuan Anh Tran

Reputation: 7237

Using async await with redis and bluebird in Nodejs

Correct me if I'm wrong here. This is what I do

client = Promise.promisifyAll(redis.createClient())
let reply = await client.getAsync('foo_rand000000000000')
console.log('reply',reply.toString())

And I got Unexpected token error.

I have this in my .babelrc

{
  "presets": [
    "es2015",
    "stage-3"
  ]
}

Can someone point what I did wrong here.

Upvotes: 2

Views: 12700

Answers (1)

aray12
aray12

Reputation: 1843

As @Bergi points out, you need to wrap that in a async function

client = Promise.promisifyAll(redis.createClient())

async function main() {
  let reply = await client.getAsync('whatever');
  console.log('reply', reply.toString());
}

main();

To expand a bit, if you look at this docs http://babeljs.io/docs/plugins/transform-async-to-generator/ you'll notice that what they are doing is converting the function to a generator and yielding the resolved value of the promise to variable reply. Without wrapping this in a function that can be converted to a generator, you won't have the ability to pause execution and, therefore, would not be able to accomplish this.

Also, it should be noted, that this is not part of the standard. It is probably not going away, but the API could change. So I would not use this unless this is a toy project. You can accomplish something very similar using co or Bluebird.coroutine. They aren't quite as aesthetically pleasing, but the API won't change and the refactor once async/await get standardized will be trivial

Edit: add further explanation

Upvotes: 9

Related Questions