p-defer/readme.md

52 lines
1.3 KiB
Markdown
Raw Permalink Normal View History

2021-01-01 10:41:38 +00:00
# p-defer
2016-10-21 05:07:52 +00:00
> Create a deferred promise
2019-03-17 12:24:05 +00:00
[Don't use this unless you know what you're doing.](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns#the-deferred-anti-pattern) Prefer the `Promise` constructor.
2016-10-21 05:07:52 +00:00
## Install
```
2019-03-17 12:24:05 +00:00
$ npm install p-defer
2016-10-21 05:07:52 +00:00
```
## Usage
```js
2021-04-09 05:21:28 +00:00
import pDefer from 'p-defer';
2016-10-21 05:07:52 +00:00
2021-04-09 05:21:28 +00:00
function delay(milliseconds) {
2016-10-21 05:07:52 +00:00
const deferred = pDefer();
2021-04-09 05:21:28 +00:00
setTimeout(deferred.resolve, milliseconds, '🦄');
2016-10-21 05:07:52 +00:00
return deferred.promise;
}
2021-04-09 05:21:28 +00:00
console.log(await delay(100));
//=> '🦄'
2016-10-21 05:07:52 +00:00
```
*The above is just an example. Use [`delay`](https://github.com/sindresorhus/delay) if you need to delay a promise.*
## API
### pDefer()
2019-06-07 08:08:42 +00:00
Returns an `object` with a `promise` property and functions to `resolve()` and `reject()`.
2016-10-21 05:07:52 +00:00
## Related
2016-11-07 09:11:47 +00:00
- [p-lazy](https://github.com/sindresorhus/p-lazy) - Create a lazy promise that defers execution until `.then()` or `.catch()` is called
2016-10-21 05:07:52 +00:00
- [More…](https://github.com/sindresorhus/promise-fun)
2019-09-10 06:12:12 +00:00
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-p-defer?utm_source=npm-p-defer&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>