Your objective is to turn the given function into a new promise, and handle success or failures from the asynchronous code.
Repo link: JavaScript Promises
- Open your command line and navigate to your repos directory (if you do not have a repos folder, then you can use mkdir repos to create one)
- Use this template repository to start a new project in your repos folder:
git clone <repo_name> - cd repo_name to navigate into your new repo directory
- Start Visual Studio Code and select 'Open Folder'. Then select repo_name to open the folder in the editor (or just type
code .in your terminal inside the repo directory) - Follow the instructions on the README.md file to complete exercises
- Open the app.js file to get started
You will start with the following code in your app.js file:
function watchTutorialCallback(callback, errorCallback) {
let userLeft = false;
if (userLeft) {
errorCallback("User left.");
} else {
callback("Thumbs up and Subscribe!");
}
}
watchTutorialCallback(
(message) => {
console.log(message);
},
(error) => {
console.log(error.name + " " + error.message);
}
);The above function can be replicated as a Promise.
- Declare a variable watching and assign it a new promise object
- Inside of the promise constructor, declare a variable named userLeft.
- Add a if/else conditional that checks if userLeft is
true - If userLeft is
true, call therejectmethod with "User left." - If
false, call the resolve method with "Thumbs up and subscribe!"
Once you have created your new promise:
- Call watching and add a promise chain using
.thenand.catch - Pass in a function callback to
.thenthat takes in a message and console.log's the message - Pass in a function callback to
.catchthat takes in an error and console.log's the error