Promisify Core Api
this is a node module who will inject new Async methods im core module of NodeJS based on Sync function with usage of callback method promisify by util.promisify(callback)
For example, in NodeJS we have in fs :
fs.readFileSync(path) : string
(bad idea)fs.readFile(path, callback: (err, content :str) => void) : void
(good but risk of callback hell)
With require this module you'll have a new function :
fs.readFileAsync(path) : Promise<content: string, err>
(Yeah a Promise, we can chain, await, etc..., help to keep a flat code ^^)
Requirements
no-one except Node 8+
The big magic is in the new util.promisify function added in Node 8.
Install
npm install promisify-core-api --save
Usage
In the earlier entry point of your program :
;
And thats it, now, everywhere on your program, you can replace a Sync
Node Core function by Async
and use use the Promise returned.
Example
With Promise style
; // at the very earlier entry point of your program, One time // somewhere in your codeconst path = ;const fs = ; // thenfs ; // catchfs ;
With async - await style
; // at the very earlier entry point of your program, One time // somewhere in your codeconst path = ;const fs = ; // async IIFE, yeah it's preaty ugly but we can't await in global scope, global scope is not asyncasync { // then try const txt = await fs; console; catch err console; // catch try const txt = await fs; console; catch err console; };
Bonus
const functions = ; console;
You will see all supported functions, and get original sync, callback api and the promisify api (function name, not directly the function).
See below part of this big object
'require(\'fs\')': sync: 'accessSync' promise: 'accessAsync' callback: 'access' sync: 'existsSync' promise: 'existsAsync' callback: 'exists' sync: 'readFileSync' promise: 'readFileAsync' callback: 'readFile' sync: 'closeSync' promise: 'closeAsync' callback: 'close' sync: 'openSync' promise: 'openAsync' callback: 'open' sync: 'readSync' promise: 'readAsync' callback: 'read' sync: 'writeSync' promise: 'writeAsync' callback: 'write' sync: 'renameSync' promise: 'renameAsync' callback: 'rename' ... ...