Promises Exercises
1 Intro
- Call the function
wait
with a callback that calls analert('Hello World')
. Promisify
the functionwait
.
2 Async/Await
const divide = (a, b) => {};
divide(8, 2).then((result) => {
if (result !== 4) {
alert("Wrong!");
} else {
alert("Correct");
}
});
divide(8, 0)
.then((result) => {
alert("Wrong!");
})
.catch((error) => {
alert("Correct!");
});
- Solve divide function
- Make divide function async
- Resolve the divide calls with await
3 Chaining
class Response {
constructor() {
this.data = "[1, 2, 3]";
}
async json() {
return JSON.parse(this.data);
}
async text() {
return this.data;
}
}
const fetch = () => {
return new Promise((resolve, reject) => {
return resolve(new Response());
});
};
-
Resolve fetch with .then
-
Resolve the .json() function of Response by using Promise chaining
-
Rewrite everything with async/await