The Promise
object
A common way to create a Promise
is by constructing it with new Promise(...)
.
A Promise
object must be initialized with a function that takes two parameters, which are often labeled resolve
and reject
(although you could call them success
and failure
, done
and failed
, etc).
This function is called immediately when the Promise
is constructed. The arguments passed to resolve
and reject
are each functions which accept a single parameter.
resolve: (value: any) => any,
reject: (error: any) => any,
) => { ... })
If resolve
is called first, then the Promise
object uses the value
argument as the final result of the asynchronous
task it represents. If reject
is called first, then the Promise
object enters an "error state" where it will produce
the error instead.
then
and catch
Once the Promise
is created, you can use its then
and catch
methods to register callback functions that should
be executed with the result of resolve
and reject
respectively. Try modifying the simple example below:
The Promise
will only call one callback function exactly once - the function registered with then
, or the function registered with catch
.
Each of these function calls returns a new Promise
which represents the result of performing some further (possibly asynchronous) work.
If either function returns a value, that value will be passed to subsequent callback functions registered
with then
or catch
.