2016-07-14 08:22:02 +08:00
|
|
|
/* eslint no-restricted-syntax: 0 */
|
|
|
|
|
2016-07-14 07:23:25 +08:00
|
|
|
require('promise.prototype.finally')
|
2016-07-14 08:22:02 +08:00
|
|
|
|
2016-07-14 07:23:25 +08:00
|
|
|
const _ = require('underscore')
|
|
|
|
|
2016-07-14 08:22:02 +08:00
|
|
|
global.Promise.props = require('promise-props');
|
2016-07-14 07:23:25 +08:00
|
|
|
|
2016-07-14 08:22:02 +08:00
|
|
|
global.Promise.each = function each(iterable, iterator) {
|
|
|
|
return Promise.resolve(iterable).then((array) => {
|
2016-07-14 07:23:25 +08:00
|
|
|
return new Promise((resolve, reject) => {
|
2016-07-14 08:22:02 +08:00
|
|
|
Array.from(array).reduce((prevPromise, item, idx, len) => (
|
2016-07-14 07:23:25 +08:00
|
|
|
prevPromise.then(() => Promise.resolve(iterator(item, idx, len)))
|
|
|
|
), Promise.resolve())
|
|
|
|
.then(() => resolve(iterable))
|
|
|
|
.catch((err) => reject(err))
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2016-07-14 08:22:02 +08:00
|
|
|
global.Promise.sleep = function sleep(ms) {
|
|
|
|
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
|
|
}
|
|
|
|
|
2016-07-14 08:40:50 +08:00
|
|
|
global.Promise.prototype.thenReturn = function thenReturn(value) {
|
|
|
|
return this.then(function then() { return Promise.resolve(value); })
|
2016-07-14 08:22:02 +08:00
|
|
|
}
|
|
|
|
|
2016-07-14 07:23:25 +08:00
|
|
|
function promisify(nodeFn) {
|
|
|
|
return function wrapper(...fnArgs) {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
nodeFn.call(this, ...fnArgs, (err, ...results) => {
|
|
|
|
if (err) {
|
|
|
|
reject(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
resolve(...results)
|
|
|
|
});
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function promisifyAll(obj) {
|
2016-07-14 08:22:02 +08:00
|
|
|
for (const key in obj) {
|
2016-07-14 07:23:25 +08:00
|
|
|
if (!key.endsWith('Async') && _.isFunction(obj[key])) {
|
|
|
|
obj[`${key}Async`] = promisify(obj[key])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return obj
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
promisify,
|
|
|
|
promisifyAll,
|
|
|
|
}
|