synchronized-promise
Version:
Turn ES6 Promise into synchronize function call, a simple wrapper of deasync package
56 lines (48 loc) • 1.56 kB
JavaScript
;
/* 10 seconds */
var DEFAULT_TIMEOUTS = 10 * 1000;
var STATE = {
INITIAL: 'INITIAL',
RESOLVED: 'RESOLVED',
REJECTED: 'REJECTED'
};
var DEFAULT_TICK = 100;
/**
* @param {Function} func Promise-base function that want to be transformed
* @param {Object} options Additional options
* @param {number} options.timeouts Function call timeouts
* @param {number} options.tick deasync tick, default to 100
* @returns {Function}
*/
function sp(func) {
var _this = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return function () {
var promiseError, promiseValue;
var promiseStatus = STATE.INITIAL;
var timeouts = options.timeouts || DEFAULT_TIMEOUTS;
var tick = options.tick || DEFAULT_TICK;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
func.apply(_this, args).then(function (value) {
promiseValue = value;
promiseStatus = STATE.RESOLVED;
}).catch(function (e) {
promiseError = e;
promiseStatus = STATE.REJECTED;
});
var waitUntil = new Date(new Date().getTime() + timeouts);
while (waitUntil > new Date() && promiseStatus === STATE.INITIAL) {
require('deasync').sleep(tick);
}
if (promiseStatus === STATE.RESOLVED) {
return promiseValue;
} else if (promiseStatus === STATE.REJECTED) {
throw promiseError;
} else {
throw new Error(`${func.name} called timeout`);
}
};
}
module.exports = sp;