0

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.

samanime
  • 25,408
  • 15
  • 90
  • 139
  • `err && reject(err) || resolve(data)` really should be `err ? reject(err) : resolve(data)` – Bergi Jun 02 '17 at 14:21
  • 1
    Yes, you can abstract this out into a helper function (or just use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)). Or use more advanced tools like `Bluebird.promisifyAll`. – Bergi Jun 02 '17 at 14:22
  • There also are a few npm libs that expose a promisified filesystem API etc, but lib requests are off-topic on SO and I cannot recommend a specific one. – Bergi Jun 02 '17 at 14:24
  • Thanks Bergi. And yeah, I'm aware of them for libraries that promisify the native libraries already. The actual ones I'm working on don't already have promise libraries. Just used `fs` as an easy example. – samanime Jun 02 '17 at 15:23

0 Answers0