UNPKG

819 BJavaScriptView Raw
1import delay from './delay.js';
2
3/**
4 * Delays the resolving of a new Promise for a given amount of time. Provides the same functionality as defer and delay, but with promises. Also serves as a wrapper for a Promise if a callback is provided.
5 *
6 * @example
7 * ``` javascript
8 * import { wait } from 'async-agent';
9 *
10 * wait(1000)
11 * .then(() => {
12 * console.log('2');
13 * });
14 *
15 * console.log('1');
16 *
17 * // => 1
18 * // (after 1000ms) => 2
19 * ```
20 *
21 * @function wait
22 *
23 * @arg {Number|function} [duration=0]
24 *
25 * @returns {Promise}
26 */
27export default (duration = 0) => new Promise((resolve, reject) => {
28 if (typeof duration === 'function') {
29 duration(resolve, reject);
30 }
31 else if (duration === 0) {
32 resolve();
33 }
34 else {
35 delay(resolve, duration);
36 }
37});