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'>
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.
(string)
top-level Error message
iterable<Error>
:
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.
(number)
the number of milliseconds to wait
promise
:
const start = Date.now()
await a.delay(5000)
console.log(Date.now() - start)
// => 5000
Waits for date
.
(date)
the date at which to stop waiting
promise
:
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
(promise)
the promise to execute
promise
:
// 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.
(EventEmitter)
the object to listen on
(string)
the event to listen for
promise<Array>
:
an array of the arguments passed to the
eventName
event
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.
promise
:
the result passed to the callback
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
.
(any)
function
:
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.
promise
:
const file = await a.single([ fetch(remoteFile), read(localFile) ])
Waits for the first count
Promises in list
to resolve.
(number?
= list.length
)
number of promises to wait for
(number?
= 0
)
number of rejections to ignore
promise<Array>
:
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.
promise<Array>
:
promised results in order
const results = await a.list([ foo, bar, baz ])
console.log(results.length)
// => 3
Waits for all Promises in the keys of container
to resolve.
promise<Object>
:
a new object with keys mapped to the resolved values
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.
(array)
items to pass to each promise
(number)
maximum concurrency
(function)
takes an item and returns a Promise
// 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
.
(any)
promise<Error>
:
the Error object, or undefined
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
.
(any)
promise
:
the result, or undefined
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.
(any)
promise
:
the result or error
$("#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.
undefined
:
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.
undefined
:
failingPromise()
// => (node:6051) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: fail
a.swallow()
failingPromise()
// (no output)