Friday, 2 June 2017

Easy pattern to convert Node-style callback functions to await/async

Is there some easy pattern that supports auto-magically converting Node-style func(params, callback) functions to await/async compatible.

I know I can convert them to promises myself, but I was wondering if since that pattern has become so common now, if there wasn't some Babel package or something that is smart enough to automatically allow us to just use them, or if I'd have to convert them all to Promises myself?

To convert it to a Promise function I can just do this (using fs.readFile as an example):

import { readFile } from 'fs';

const readFilePromise = path => new Promise((resolve, reject) => readFile(path, (err, data) => err && reject(err) || resolve(data)));

That's simple enough, but it's a pain to have to convert every function I want in that fashion.



via samanime

No comments:

Post a Comment