...

/

Returning Values from Promises

Returning Values from Promises

Learn how to return values from promises and the rules we must follow while doing so.

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 true
function 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 argument
reject: (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
}
);
}
Promise returning a string with an error
  • We have a function named promiseReturningString that has a single input argument named throwError, which is of type boolean.

  • 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 the throwError input parameter to either call the reject or resolve callback function.

  • Note, however, the format of the resolve callback function on line 8. It returns a type of void but has a single input parameter named outputValue of type string. 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 ...