Returning Values from Promises
Learn how to return values from promises and the rules we must follow while doing so.
We'll cover the following...
Introduction
Most Promises will, in fact, return some sort of information when called, and we use the generic syntax when we construct a Promise in order to indicate what type it will return. Thus far, we have been using Promise<void>
to indicate that the Promise will return a type void
, or in other words, will not return any data. We can use Promise<string>
to indicate that the Promise will return a string
as follows:
// A function that returns a promise that resolves with a string// or rejects with an error code if `throwError` is truefunction promiseReturningString(throwError: boolean): Promise<string> {return new Promise<string>(// The promise constructor takes a function that receives two callbacks:// `resolve` and `reject`(resolve: (outputValue: string) => void, // The `resolve` callback accepts a single string argumentreject: (errorCode: number) => void // The `reject` callback accepts a single number argument) => {if (throwError) {reject(101); // If `throwError` is true, reject with error code 101}resolve(`resolve with message`); // Otherwise, resolve with the given string message});}
-
We have a function named
promiseReturningString
that has a single input argument namedthrowError
, which is of typeboolean
. -
This function returns a Promise that uses generic syntax to indicate that it will return a Promise of type
string
. The body of the function constructs and returns a new Promise object. Within the body of the Promise, we use thethrowError
input parameter to either call thereject
orresolve
callback function. -
Note, however, the format of the
resolve
callback function on line 8. It returns a type ofvoid
but has a single input parameter namedoutputValue
of typestring
. This is the method of returning values from Promises.
Remember that within our Promise code, when we invoke the resolve
callback function, we provide a single argument of the type that was specified as the Promise generic type. This can be seen when we invoke the resolve
function, which has now become resolve(resolve with message)
on line 14. So, if we define a Promise<string>
, then the resolve
function signature must have a single parameter of type string
.
Note that it is only the resolve
callback signature that ...