makepromise
![npm version](https://badge.fury.io/js/makepromise.svg)
Make native Promise
from function with callback.
ES5
The package uses some newer language features. For your convenience, it's been
transpiled to be compatible with Node 4. You can use the following snippet.
const makePromise = require('makepromise/es5/src/')
makePromise(fn:Function(...args, cb:Function(err:Error, res:any))) => Promise<any>
Create a promise from a function which accepts a callback as the last argument,
and where the callback will be called with 2 arguments: (error, result)
.
For example, you can unlink a file (here, a temp file is created with
wrote
package):
const { unlink } = require('fs')
const { createWritable } = require('wrote')
const makePromise = require('makepromise')
let file
(async () => {
const ws = await createWritable()
const { path: file } = ws
await new Promise((resolve, reject) => {
ws.once('close', resolve)
ws.once('error', reject)
ws.close()
})
await makePromise(unlink, file)
})()
In addition, errors will be updated to include the stack trace of when
makePromise
was called, rather than have node internal error stack, or no
stack at all:
const fs = require('fs')
const makePromise = require('makepromise');
(async () => {
try {
await makePromise(fs.unlink, 'error-test-file')
} catch ({ stack }){
console.log(stack)
}
})()
makePromise(fn:Function(...args, cb:Function(err:Error, res:any), resolveValue:any)) => Promise<any>
Pass resolveValue
as second argument to make promise be resolved with it.
const { unlink } = require('fs')
const { createWritable } = require('wrote')
const makePromise = require('makepromise');
(async () => {
const ws = await createWritable()
await closeWritable(ws)
const { path: file } = ws
console.log(file)
const resolvedFile = await makePromise(unlink, file, file)
console.log(resolvedFile === file)
})()
More examples
Check test/spec/integration
for the following tests:
Licence: MIT
(c) Sobesednik-Media 2017