UNPKG

1.98 kBJavaScriptView Raw
1/**
2 * @copyright Copyright (c) 2019 Maxim Khorin <maksimovichu@gmail.com>
3 */
4'use strict';
5
6module.exports = class PromiseHelper {
7
8 static setTimeout (timeout) {
9 return new Promise(resolve => setTimeout(resolve, timeout));
10 }
11
12 static setImmediate () {
13 return new Promise(resolve => setImmediate(resolve));
14 }
15
16 static promise (callback, context) {
17 return new Promise((resolve, reject) => {
18 callback.call(context, (err, result) => {
19 err ? reject(err) : resolve(result);
20 });
21 });
22 }
23
24 static callback (promise, callback) {
25 return callback
26 ? promise.then(result => callback(null, result), callback)
27 : promise;
28 }
29
30 static async each (items, handler, context) {
31 if (Array.isArray(items)) {
32 for (const item of items) {
33 await handler.call(context, item);
34 }
35 }
36 }
37
38 static async eachOf (data, handler, context) {
39 if (data) {
40 for (const key of Object.keys(data)) {
41 await handler.call(context, data[key], key);
42 }
43 }
44 }
45
46 static async eachMethod (items, method) {
47 if (Array.isArray(items)) {
48 for (const item of items) {
49 await item[method]();
50 }
51 }
52 }
53
54 static async map (items, handler, context) {
55 const result = [];
56 if (Array.isArray(items)) {
57 for (const item of items) {
58 result.push(await handler.call(context, item));
59 }
60 }
61 return result;
62 }
63
64 static async mapValues (data, handler, context) {
65 const result = {};
66 if (data) {
67 for (const key of Object.keys(data)) {
68 result[key] = await handler.call(context, data[key], key);
69 }
70 }
71 return result;
72 }
73};
\No newline at end of file