...

/

Promise Syntax

Promise Syntax

Learn to create Promises in JavaScript with functions, callbacks, and error handling.

The code examples that we have seen up until now have used Promises that are provided by a third-party library, such as the Promise-based versions of filesystem access available through the Node fs.promise namespace. So, how do we write our own Promises?

Writing Promises

A Promise is an instance of a new Promise class whose constructor requires a function signature that accepts two callback functions, generally named resolve and reject.

Consider the following function definition:

// This function takes two arguments, both of which are functions.
function fnDelayedPromise(
resolve: () => void, // This function will be called when the promise is resolved.
reject: () => void // This function will be called when the promise is rejected.
) {
// This function will be called after a timeout of 1000ms (1 second).
function afterTimeout() {
resolve();
}
// Set a timeout of 1000ms and call the afterTimeout function when the timeout expires.
setTimeout(afterTimeout, 1000);
}
Delay Promise with timeout function
  • We have a function named fnDelayedPromise that accepts two functions as parameters, named resolve and reject, both returning void. Within the body of this function, we define a callback function named afterTimeout on lines 7–9, which will invoke the resolve callback that was passed in as the first argument.

  • It then calls the setTimeout function on line 11, which will cause a one-second delay before ...