Debian Codegraph @

timers-ext/promise_/timeout.js

raw
1 "use strict";
2
3 var customError = require("es5-ext/error/custom")
4 , isValue = require("es5-ext/object/is-value")
5 , ensurePromise = require("es5-ext/object/ensure-promise")
6 , nextTick = require("next-tick")
7 , ensureTimeout = require("../valid-timeout");
8
9 module.exports = function (/* timeout */) {
10 ensurePromise(this);
11 var timeout = arguments[0];
12 if (isValue(timeout)) timeout = ensureTimeout(timeout);
13 return new this.constructor(
14 function (resolve, reject) {
15 var isSettled = false, timeoutId;
16 var timeoutCallback = function () {
17 if (isSettled) return;
18 reject(
19 customError(
20 "Operation timeout (exceeded " +
21 (isValue(timeout) ? timeout + "ms" : "tick") +
22 ")",
23 "PROMISE_TIMEOUT"
24 )
25 );
26 };
27 if (isValue(timeout)) timeoutId = setTimeout(timeoutCallback, timeout);
28 else nextTick(timeoutCallback);
29 this.then(
30 function (value) {
31 isSettled = true;
32 clearTimeout(timeoutId);
33 resolve(value);
34 }, function (reason) {
35 isSettled = true;
36 clearTimeout(timeoutId);
37 reject(reason);
38 }
39 );
40 }.bind(this)
41 );
42 };