Node.js utils to deal with async/await.
npm install --save mono-utilsINFO: You need node >= 8.0.0 to use mono-utils since it uses native async/await
const { ok, cb, waitFor, ... } = require('mono-utils')Waits for the value of the Promise and returns its value. If the promise throws an Error, returns undefined.
ok(promise: Object): PromiseExample:
const { ok } = require('mono-core/utils')
const { readFile } = require('fs-extra')
// readFile sends back a Promise since we use fs-extra
const file = await ok(readFile('./my-file.txt', 'utf-8'))
if (file) console.log('File found:', file)Calls a function Node style function as first argument function (err, result), all the others arguments will be given to the function. Waits for the callback result, throws an Error if err is truthy.
cb(fn: Function, ...args: any[]): PromiseExample:
const { ok } = require('mono-core/utils')
const fs = require('fs')
try {
const file = await cb(fs.readFile, '/path/to/my/file.txt', 'utf-8')
} catch (err) {
// Could not read file
}Waits for ms milliseconds to pass, use setTimeout under the hood.
waitFor(ms: number): PromiseExample:
const { waitFor } = require('mono-core/utils')
await waitFor(1000) // wait for 1sWaits for emitter to emit an eventName event.
waitForEvent(emitter: EventEmitter, eventName: string, timeout: number = -1): Promise<Array>Example:
const { waitFor } = require('mono-core/utils')
await waitForEvent(sever, 'listen')Waits for all Promises in the keys of obj to resolve.
asyncObject(obj: Object): Promise<Object>Example:
const { asyncObject } = require('mono-core/utils')
const { pictures, comments, tweets } = await asyncObject({
pictures: getPictures(),
comments: getComments(),
tweets: getTweets()
})
console.log(pictures, comments, tweets)Waits for all Promises mapped by fn:
asyncMap(array: Array, fn: Function): Promise<Array>Example:
const { asyncMap } = require('mono-core/utils')
const posts = await asyncMap([1, 2, 3], (id) => fetchPost(id))Loop for every item in array and call fn and wait for it to finish in series:
asyncForEach(array: Array, fn: Function): Promise<void>Example:
const { asyncMap } = require('mono-core/utils')
const posts = await asyncForEach(users, async (user) => {
await saveUser(user)
})We developed other utils that you might find useful:
