Mailspring/packages/nylas-core/promise-utils.js

56 lines
1.3 KiB
JavaScript
Raw Normal View History

2016-07-14 08:22:02 +08:00
/* eslint no-restricted-syntax: 0 */
require('promise.prototype.finally')
2016-07-14 08:22:02 +08:00
const _ = require('underscore')
2016-07-14 08:22:02 +08:00
global.Promise.props = require('promise-props');
2016-07-14 08:22:02 +08:00
global.Promise.each = function each(iterable, iterator) {
return Promise.resolve(iterable).then((array) => {
return new Promise((resolve, reject) => {
2016-07-14 08:22:02 +08:00
Array.from(array).reduce((prevPromise, item, idx, len) => (
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))
}
global.Promise.prototype.thenReturn = function thenReturnPolyfill(value) {
this.then(function then() { return Promise.resolve(value); })
}
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) {
if (!key.endsWith('Async') && _.isFunction(obj[key])) {
obj[`${key}Async`] = promisify(obj[key])
}
}
return obj
}
module.exports = {
promisify,
promisifyAll,
}