# makepromise

[![npm version](https://badge.fury.io/js/makepromise.svg)](https://badge.fury.io/js/makepromise)

Make native Promise from function with callback

## `makePromise(fn:Function(...args, cb:Function(err:Error, res:any))) => Promise<any>`

Create a promise from a function which accepts callback as the last argument,
and where callback will be called with (error, result).

For example, you can unlink a closed file:

```js
'use strict'

const fs = require('fs')
const wrote = require('wrote')
const makePromise = require('makepromise')

let file
wrote() // create a temp file and open a writable stream
    .then((ws) => {
        file = ws.path
        console.log(ws.path) // /var/folders/s0/tmp/T/wrote-69822.data
        return new Promise((resolve, reject) => {
            ws.once('close', resolve)
            ws.once('error', reject)
            ws.close()
        })
    })
    .then(() => {
        const promise = makePromise(fs.unlink, file)
        return promise
    })
    .then(
        console.log, // undefined
        console.error
    )

```

## `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.

```js
'use strict'

const fs = require('fs')
const wrote = require('wrote')
const makePromise = require('makepromise')

let file
wrote() // create a temp file and open a writable stream
    .then((ws) => {
        file = ws.path
        console.log(ws.path) // /var/folders/s0/tmp/T/wrote-69822.data
        return new Promise((resolve, reject) => {
            ws.once('close', resolve)
            ws.once('error', reject)
            ws.close()
        })
    })
    .then(() => {
        const promise = makePromise(fs.unlink, file, file)
        return promise
    })
    .then(
        (res) => { console.log(res === file) }, // true
        console.error
    )
```

## More examples

Check `test/spec/integration` for the following tests:

* How to [unlock a file with](https://github.com/Sobesednik/makepromise/blob/master/test/spec/integration.js#L15)
[`lockfile`](https://www.npmjs.com/package/lockfile) and close write stream
* [How to write to a file stream](https://github.com/Sobesednik/makepromise/blob/master/test/spec/integration.js#L45) open with `fs.createWriteStream()` and end the stream
* How to [unlink a file](https://github.com/Sobesednik/makepromise/blob/master/test/spec/integration.js#L73) with `fs.unlink`
* How to [read stat](https://github.com/Sobesednik/makepromise/blob/master/test/spec/integration.js#L99) with `fs.stat`
* How to catch errors (example with trying to [call `fs.stat` with non-existent file](https://github.com/Sobesednik/makepromise/blob/master/test/spec/integration.js#L114))

---

Licence: MIT

*(c) [Sobesednik-Media](https://sobesednik.media) 2017*

