Coding diary to reflect concepts that I am learning and revisiting
Promises
console.log("A");
wait(1000).then(()=> {
console.log("B");
});
console.log("C");
/* OUTPUT
A
C
B (after 1 second)
*/
JavaScript- You can only can
then()
on functions that returns a new promise - Several Web APIs (which are functions in the browswer) return promises. Examples of such Web APIs include
fetch
andgetUserMedia
(which is for accessing camera and audio)
A promise has 3 different states:
- Pending
- Creating a promise starts the pending state
- fulfiled
- When the promise is completed the callback gets passed to
.then(callback)
which will be executed
- When the promise is completed the callback gets passed to
- Rejected
getWeatherConditions(city)
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
JavaScript- When a promise is successfully completed it becomes fulfilled
Promise finally()
- The
.finally()
callback executed whenever the state of a promise changes from pending to fulfilled or from pending to rejected finally()
executes when the promise fails or succeeds
Manually rejecting a promise
A promise can be manually rejected by throwing an error
E.g.
getWeatherCondition(city)
.then(data => {
throw new Error("Stop!!!.")
console.log(`Info ${data}`); // not executed
})
.catch(error => {
console.error(error); // executed
})
JavaScriptCreating Promises
const waitOneSecond = () => {
return new Promise((resolve) => {
resolve();
})
}
JavaScriptTopics Reviewed:
- reduce()
- nullish coalescing and optional chaining
- Using
Object.keys()
to get an array of all the keys in an object - Using
Object.values()
to get an array of all the values in an object - Using
Object.entries()
to get a 2D array for an object