The async/await utility for browsers and Node.js.

( examples - github - npm - suggestions / bug reports - installation - motivation )

$ yarn add awaiting

$ npm install awaiting --save

<script src='awaiting.js'>

Build Status Coverage Status

awaiting
License: MIT
Example
const a = require('awaiting')
// ...
await a.delay(1000)

Iterable Error type

Functions that operate on lists throw ErrorLists, making it possible to inspect all of the Errors that may have been thrown.

new ErrorList(message: string): iterable<Error>
Parameters
message (string) top-level Error message
Returns
iterable<Error>:
Example
const err = new ErrorList('several errors')
err.add(new Error('first'))
err.add(new Error('second'))
console.log(err.message, err.get(1).message)
// => several errors second
try {
  await a.list([ failing1, failing2, failing3 ])
}
catch (errorList) {
  for (let err of errorList) {
    console.error(err.stack)
  }
}

Waits for ms milliseconds to pass.

delay(ms: number): promise
Parameters
ms (number) the number of milliseconds to wait
Returns
promise:
Example
const start = Date.now()
await a.delay(5000)
console.log(Date.now() - start)
// => 5000

Waits for date.

time(date: date): promise
Parameters
date (date) the date at which to stop waiting
Returns
promise:
Example
const nextYear = new Date(2018, 1)
await a.time(nextYear)
// => this will run until the end of 2017

Waits for the value of goal, limited by the resolution of limiter. Throws an Error if limiter finishes first or if either throws early. If limiter is a number, limits by time in milliseconds

limit(goal: promise, limiter: (number | promise)): promise
Parameters
goal (promise) the promise to execute
limiter ((number | promise)) milliseconds or promise to limit by
Returns
promise:
Example
// throw if flowers.jpg can't be retrieved in < 5 seconds
await a.limit(fetch('flowers.jpg'), 5000)

Waits for emitter to emit an eventName event.

event(emitter: EventEmitter, eventName: string): promise<Array>
Parameters
emitter (EventEmitter) the object to listen on
eventName (string) the event to listen for
Returns
promise<Array>: an array of the arguments passed to the eventName event
Example
await a.event(server, 'listen')

Calls a function func that takes arguments args and an (err, result) callback. Waits for the callback result, throwing an Error if err is truthy.

callback(fn: function, args: ...object): promise
Parameters
fn (function) a function that takes a callback
args (...object) arguments to pass to fn
Returns
promise: the result passed to the callback
Example
const result = await a.callback(fs.readFile, 'foo.txt')
console.log(result)
// => 'the text of the file'

Wraps a node style function (see callback) into a new function, which instead of taking a callback function, returns an async function (Promise). This Promise resolves if the first (error) argument of the callback was called with a falsy value, rejects with the error otherwise. Takes the rest of the arguments as the original function fn.

awaited(fn: any): function
Parameters
fn (any)
Returns
function:
Example
const fs = require('fs')
const readFile = a.awaited(fs.readFile)
const contents = await readFile('foo.txt', 'utf-8')

Waits for the first Promise in list to resolve.

single(list: array<Promise>, ignore: number?): promise
Parameters
list (array<Promise>) racing promises
ignore (number? = 0) number of rejections to ignore
Returns
promise:
Example
const file = await a.single([ fetch(remoteFile), read(localFile) ])

Waits for the first count Promises in list to resolve.

set(list: array<Promise>, count: number?, ignore: number?): promise<Array>
Parameters
list (array<Promise>) racing promises
count (number? = list.length) number of promises to wait for
ignore (number? = 0) number of rejections to ignore
Returns
promise<Array>:
Example
const [ first, second ] = await a.set([
  ping('ns1.example.com'),
  ping('ns2.example.com'),
  ping('ns3.example.com'),
  ping('ns4.example.com')
], 2)
console.log(`fastest nameservers: ${first}, ${second}`)

Waits for all Promises in list to resolve.

Like Promise.all with the option to ignore some (or all) rejections.

list(list: array, ignore: number?= 0): promise<Array>
Parameters
list (array) promises
ignore (number?= 0) rejections to ignore
Returns
promise<Array>: promised results in order
Example
const results = await a.list([ foo, bar, baz ])
console.log(results.length)
// => 3

Waits for all Promises in the keys of container to resolve.

object(container: object, ignore: number?= 0): promise<Object>
Parameters
container (object)
ignore (number?= 0) rejections to ignore
Returns
promise<Object>: a new object with keys mapped to the resolved values
Example
const results = await a.object({
  pictures: getPictures(),
  comments: getComments(),
  tweets: getTweets()
})
console.log(results.pictures, results.comments, results.tweets)

Passes each item in list to the Promise-returning function fn, running at most concurrency simultaneous promises.

For cases where starting all Promises simultaneously is infeasible, such as making a large number of requests to a server with rate-limiting.

map(list: array, concurrency: number, fn: function)
Parameters
list (array) items to pass to each promise
concurrency (number) maximum concurrency
fn (function) takes an item and returns a Promise
Example
// pull hundreds of pages from a site without getting blocked
const pages = await a.map(urls, 3, fetch)

Waits for promise to reject, returning the Error object. If promise resolves successfully, returns undefined.

failure(promise: any): promise<Error>
Parameters
promise (any)
Returns
promise<Error>: the Error object, or undefined
Example
test('throws "foo"', () => {
  const err = await a.failure(shouldThrow())
  assert.equal(err.message, 'foo')
})

Waits for the value of promise. If promise throws an Error, returns undefined.

success(promise: any): promise
Parameters
promise (any)
Returns
promise: the result, or undefined
Example
const isNodeProject = await a.success(a.callback(fs.access, packageJSON))
if (isNodeProject) doSomething()

Waits for promise to resolve or reject. Returns either the resolved value, or the Error object.

result(promise: any): promise
Parameters
promise (any)
Returns
promise: the result or error
Example
$("#ajax-loader-animation").show()
await a.result(loadAjaxData())
$("#ajax-loader-animation").hide();

Provides a stack trace for unhandled rejections instead of the default message string.

throw and swallow can be called multiple times but will only attach a single listener.

throw(): undefined
Returns
undefined:
Example
failingPromise()
// => (node:6051) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: fail
a.throw()
failingPromise()
// => /Users/hloftis/code/awaiting/lib/awaiting.js:308
// => function throwOnRejection (err, promise) { throw err }
// =>                                            ^
// => Error: fail
// =>    at fail (/Users/hloftis/code/awaiting/test/fixtures/rejection-throw.js:7:9)
// =>    at Object.<anonymous> (/Users/hloftis/code/awaiting/test/fixtures/rejection-throw.js:4:1)

Silently swallows unhandled rejections.

This is an anti-pattern, but if you depend on a module that doesn't handle all of its rejections, you'll get a lot of really annoying logs in current versions of node. swallow will allow you to suppress them.

throw and swallow can be called multiple times but will only attach a single listener.

swallow(): undefined
Returns
undefined:
Example
failingPromise()
// => (node:6051) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: fail
a.swallow()
failingPromise()
// (no output)