Skip to content

Commit

Permalink
feat(promise): sleep util
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Mar 13, 2018
1 parent a4c0647 commit c50d575
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
3 changes: 3 additions & 0 deletions promise/.eslintrc.json
@@ -0,0 +1,3 @@
{
"globals": { "Promise": true }
}
21 changes: 21 additions & 0 deletions promise/sleep.js
@@ -0,0 +1,21 @@
"use strict";

var isValue = require("es5-ext/object/is-value")
, isPromise = require("es5-ext/object/is-promise")
, nextTick = require("next-tick")
, ensureTimeout = require("../valid-timeout");

module.exports = function (/* timeout */) {
var Constructor = isPromise(this) ? this.constructor : Promise;
var timeout = arguments[0];
if (isValue(timeout)) timeout = ensureTimeout(timeout);
return new Constructor(function (resolve) {
if (isValue(timeout)) {
setTimeout(function () {
resolve();
}, timeout);
} else {
nextTick(resolve);
}
});
};
34 changes: 34 additions & 0 deletions test/promise/sleep.js
@@ -0,0 +1,34 @@
"use strict";

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

module.exports = function (t, a) {
if (typeof Promise !== "function") return null;
return {
Tick: function (d) {
var isInvoked = false;
t().then(function (result) {
isInvoked = true;
delay(function () {
a(result, undefined);
d();
})();
}, delay(d));
a(isInvoked, false);
},
Timeout: function (d) {
var isInvoked = false;
t(100).then(
delay(function (result) {
isInvoked = true;
a(result, undefined);
d();
}),
delay(d)
);
setTimeout(function () {
a(isInvoked, false);
}, 50);
}
};
};

0 comments on commit c50d575

Please sign in to comment.