Skip to content

Commit

Permalink
feat(promise): promise.timeout method
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Mar 7, 2018
1 parent 5376dbd commit 3f52d27
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 0 deletions.
34 changes: 34 additions & 0 deletions promise_/timeout.js
@@ -0,0 +1,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)
);
};
3 changes: 3 additions & 0 deletions test/promise_/.eslintrc.json
@@ -0,0 +1,3 @@
{
"globals": { "Promise": true }
}
50 changes: 50 additions & 0 deletions test/promise_/timeout.js
@@ -0,0 +1,50 @@
"use strict";

var delay = require("../../delay");

module.exports = function (t, a) {
if (typeof Promise !== "function") return null;
return {
Success: function (d) {
var promise = t.call(
new Promise(function (resolve) {
setTimeout(function () {
resolve("foo");
}, 20);
}),
40
);

promise.then(
// Delay to escape error swallowing
delay(function (result) {
a(result, "foo");
d();
}),
delay(d)
);
},
Timeout: function (d) {
var promise = t.call(
new Promise(function (resolve) {
setTimeout(function () {
resolve("foo");
}, 40);
}),
20
);

promise.then(
// Delay to escape error swallowing
delay(function () {
a.never();
d();
}),
delay(function (err) {
a(err.code, "PROMISE_TIMEOUT");
d();
})
);
}
};
};

0 comments on commit 3f52d27

Please sign in to comment.