| 1 |
// 'timeout' - Promise extension |
| 2 |
// |
| 3 |
// promise.timeout(ms) |
| 4 |
// |
| 5 |
// Resolves with resolution value of context promise assuming it settles before timeout time passes |
| 6 |
// Otherwise resolves with timeout rejection |
| 7 |
|
| 8 |
"use strict"; |
| 9 |
|
| 10 |
var customError = require("es5-ext/error/custom") |
| 11 |
, isValue = require("es5-ext/object/is-value") |
| 12 |
, nextTick = require("next-tick") |
| 13 |
, ensureTimeout = require("timers-ext/valid-timeout") |
| 14 |
, deferred = require("../../deferred"); |
| 15 |
|
| 16 |
deferred.extend( |
| 17 |
"timeout", |
| 18 |
function (timeout) { |
| 19 |
var def; |
| 20 |
var callback = function () { |
| 21 |
if (this.resolved) return; |
| 22 |
def.reject(customError("Operation timeout", "DEFERRED_TIMEOUT")); |
| 23 |
}.bind(this); |
| 24 |
if (isValue(timeout)) setTimeout(callback, ensureTimeout(timeout)); |
| 25 |
else nextTick(callback); |
| 26 |
if (!this.pending) this.pending = []; |
| 27 |
def = deferred(); |
| 28 |
this.pending.push("timeout", [def.promise, def.resolve]); |
| 29 |
return def.promise; |
| 30 |
}, |
| 31 |
function (promise, resolve) { if (!promise.resolved) resolve(this); }, |
| 32 |
function (timeout) { |
| 33 |
if (isValue(timeout)) ensureTimeout(timeout); |
| 34 |
return this; |
| 35 |
} |
| 36 |
); |