-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeout.js
34 lines (32 loc) · 938 Bytes
/
timeout.js
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
"use strict";
var customError = require("es5-ext/error/custom")
, isValue = require("es5-ext/object/is-value")
, ensurePromise = require("es5-ext/object/ensure-promise")
, nextTick = require("next-tick")
, ensureTimeout = require("../valid-timeout");
module.exports = function (/* timeout */) {
ensurePromise(this);
var timeout = arguments[0];
if (isValue(timeout)) timeout = ensureTimeout(timeout);
return new this.constructor(
function (resolve, reject) {
var isSettled = false;
this.then(
function (value) {
isSettled = true;
resolve(value);
},
function (reason) {
isSettled = true;
reject(reason);
}
);
var timeoutCallback = function () {
if (isSettled) return;
reject(customError("Operation timeout", "PROMISE_TIMEOUT"));
};
if (isValue(timeout)) setTimeout(timeoutCallback, timeout);
else nextTick(timeoutCallback);
}.bind(this)
);
};