Coding Diary: JavaScript Learning Log 5

gravatar
By Ranti
 · 
February 10, 2023
 · 
2 min read

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 and getUserMedia (which is for accessing camera and audio)

A promise has 3 different states:

  1. Pending
    • Creating a promise starts the pending state
  2. fulfiled
    • When the promise is completed the callback gets passed to .then(callback) which will be executed
  3. 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
	})
JavaScript

Creating Promises

const waitOneSecond = () => {
	return new Promise((resolve) => {
		resolve();
	})
}
JavaScript

Topics 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

View