Practice creating your own promises
You may have used promises provided by libraries or built-in functions before. For example:
A promise is an object with a .then
method. This method takes a callback function that it will call with the result when the promise is finished (or "resolved"). You can imagine a promise object looks something like this:
But how do you create your own promise objects?
You can create your own promise objects with new Promise()
. You have to pass in a function that defines when the promise will resolve or reject. This function is passed two arguments: resolve
and reject
. These are functions you call with the value you want to resolve/reject with.
For example:
You could use the above just like any other promise-returning function:
You're going to create a promisified version of setTimeout
, called wait
. It should take a number of millliseconds to wait as an argument, set a timeout for that long, then resolve the promise.
It should be usable like this:
You can run the tests to check if your solution works:
You're going to create your own promisified wrapper of Node's fs.readFile
method. It usually takes a callback to be run when it finishes its asynchronous task.
Implement the readFilePromise
function so that it returns a new promise. It should use fs.readFile
to read whatever file path is passed in, then resolve with the result. It should reject with any error that occurred. For example:
You can run the tests to check if your solution works: