Promise Syntax
Learn to create Promises in JavaScript with functions, callbacks, and error handling.
We'll cover the following...
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);}
-
We have a function named
fnDelayedPromisethat accepts two functions as parameters, namedresolveandreject, both returningvoid. Within the body of this function, we define a callback function namedafterTimeouton lines 7–9, which will invoke theresolvecallback that was passed in as the first argument. -
It then calls the
setTimeoutfunction on line 11, which will cause a one-second delay before ...