| 1 |
# delay [](https://travis-ci.org/sindresorhus/delay) |
| 2 |
|
| 3 |
> Delay a promise a specified amount of time |
| 4 |
|
| 5 |
|
| 6 |
## Install |
| 7 |
|
| 8 |
``` |
| 9 |
$ npm install --save delay |
| 10 |
``` |
| 11 |
|
| 12 |
|
| 13 |
## Usage |
| 14 |
|
| 15 |
```js |
| 16 |
const delay = require('delay'); |
| 17 |
|
| 18 |
delay(200) |
| 19 |
.then(() => { |
| 20 |
// executed after 200 milliseconds |
| 21 |
}); |
| 22 |
|
| 23 |
somePromise() |
| 24 |
.then(delay(100)) |
| 25 |
.then(result => { |
| 26 |
// executed 100 milliseconds after somePromise resolves |
| 27 |
// the result from somePromise is passed through |
| 28 |
}); |
| 29 |
|
| 30 |
// and with Babel and async functions |
| 31 |
async () => { |
| 32 |
bar(); |
| 33 |
|
| 34 |
await delay(100); |
| 35 |
|
| 36 |
// executed 100 milliseconds later |
| 37 |
baz(); |
| 38 |
}(); |
| 39 |
|
| 40 |
// there's also delay.reject() that takes the value, and rejects it `ms` later |
| 41 |
Promise.resolve('foo') |
| 42 |
.then(delay.reject(100)) |
| 43 |
.then(x => blah()) // never executed |
| 44 |
.catch(err => { |
| 45 |
// executed 100 milliseconds later |
| 46 |
// err === 'foo' |
| 47 |
}); |
| 48 |
|
| 49 |
// you can also specify the rejection value |
| 50 |
Promise.resolve('foo') |
| 51 |
.then(delay.reject(100, 'bar')) |
| 52 |
.then(x => blah()) // never executed |
| 53 |
.catch(err => { |
| 54 |
// executed 100 milliseconds later |
| 55 |
// err === 'bar' |
| 56 |
}); |
| 57 |
``` |
| 58 |
|
| 59 |
|
| 60 |
## Related |
| 61 |
|
| 62 |
- [immediate-promise](https://github.com/sindresorhus/immediate-promise) - Returns a promise resolved in the next event loop - think `setImmediate()` |
| 63 |
|
| 64 |
|
| 65 |
## License |
| 66 |
|
| 67 |
MIT © [Sindre Sorhus](http://sindresorhus.com) |