Asynchronous Coding
javascript.into -> Promises, async/await
Callbacks
error-first callback style
// callback where err will be null if successful
callback(err, result);
// used like
loadScript('/my/script.js', function(error, result) {
if (error) {
// handle error
} else {
// script loaded successfully - result has a value
}
});
Callback hell or pyramid of doom
The style with callbacks in callbacks, leads to deeply nested structures.
It can be unwrapped by making each level into its own function.
Promises
let promise = new Promise(function(resolve, reject) {
// executor (the producing code)
// if it succeeds it should call
resolve(data);
// if it fails it should call
reject(new Error(..));
});
The promise
object returned by the new Promise
constructor has these internal properties:
state
— initiallypending
, then changes to eitherfulfilled
whenresolve
is called orrejected
whenreject
is called.result
— initiallyundefined
, then changes tovalue
whenresolve(value)
is called orerror
whenreject(error)
is called.
A promise
that is either fulfilled
or rejected
is called settled
, as opposed to an initially pending
promise.
The state
and result
are internal
The properties state
and result
of the Promise
object are internal. They can not be accessed, but the promise
methods .then
/ .catch
/ .finally
are used for that.
Promise.all(iterable)
, etc.
Promise.all(iterable)
Promise.allSettled(iterable)
Promise.race(iterable)
Promise.reject(reason)
Promise.resolve(value)