Using async await with redis and bluebird in Nodejs
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
Related videos on Youtube
Tuan Anh Tran
BY DAY: Node.js guru BY NIGHT: I write code for fun. Blog sometimes at https://tuananh.net
Updated on June 04, 2022Comments
-
Tuan Anh Tran almost 2 years
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.
-
BergiDid you put that code inside an
async function
?
-
-
jonathancardoso over 7 yearsThis was implemented into the spec for ECMA262: github.com/tc39/ecma262/pull/692