1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function(require) {
var env = require('../env');
var TimeoutError = require('../TimeoutError');
function setTimeout(f, ms, x, y) {
return env.setTimer(function() {
f(x, y, ms);
}, ms);
}
return function timed(Promise) {
/**
* Return a new promise whose fulfillment value is revealed only
* after ms milliseconds
* @param {number} ms milliseconds
* @returns {Promise}
*/
Promise.prototype.delay = function(ms) {
var p = this._beget();
this._handler.fold(handleDelay, ms, void 0, p._handler);
return p;
};
function handleDelay(ms, x, h) {
setTimeout(resolveDelay, ms, x, h);
}
function resolveDelay(x, h) {
h.resolve(x);
}
/**
* Return a new promise that rejects after ms milliseconds unless
* this promise fulfills earlier, in which case the returned promise
* fulfills with the same value.
* @param {number} ms milliseconds
* @param {Error|*=} reason optional rejection reason to use, defaults
* to a TimeoutError if not provided
* @returns {Promise}
*/
Promise.prototype.timeout = function(ms, reason) {
var p = this._beget();
var h = p._handler;
var t = setTimeout(onTimeout, ms, reason, p._handler);
this._handler.visit(h,
function onFulfill(x) {
env.clearTimer(t);
this.resolve(x); // this = h
},
function onReject(x) {
env.clearTimer(t);
this.reject(x); // this = h
},
h.notify);
return p;
};
function onTimeout(reason, h, ms) {
var e = typeof reason === 'undefined'
? new TimeoutError('timed out after ' + ms + 'ms')
: reason;
h.reject(e);
}
return Promise;
};
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
|