Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3d05646

Browse files
committed
Promises DONE
1 parent e69af25 commit 3d05646

File tree

1 file changed

+233
-0
lines changed

1 file changed

+233
-0
lines changed

β€Ž12-Asynchronous-JavaScript.mdβ€Ž

Lines changed: 233 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,3 +221,236 @@ In this example, we call the `downloadImage` function with a URL and a `process(
221221
Once the image is downloaded, the `callback` function is called with the url of the downloaded image as an argument. In this case, the `callback` fucntion is the `process` function. The `process` function is executed asynchronously, after the image is downlaoded and the `callback` fucntion is called.
222222
223223
_Note_: `setTimeout` is not a part of JavaScript engine but it is a part of Web APIs (in browsers).
224+
225+
## Promises
226+
227+
Promises are alo a way to handle asynchronous functions in JavaScript. Promises provides us a cleaner and more structured way to write asynchronous code than callbacks. A `Promise` is an object that represents the **success** or **failure** of an asynchronous code and provides a way to handle the result of that operation once it is completed.
228+
229+
A `Promise` has three possible states: `Pending`, `Fulfilled`, `Rejected`. `Promise` starts in `Pending` state and will either be `Fulfilled` with a value or `Rejected` with an error message.
230+
231+
- _pending_: initial state
232+
- _fulfilled_: operation was completed successfully
233+
- _rejected_: operation failed
234+
235+
When we create a new `Promise`, we pass in a function that takes two arguments, `resolve` and `reject`. These arguments are functions themselves that we can call when the asynchronous operation is complete.
236+
237+
```js
238+
const myPromise = new Promise((resolve, reject) => {
239+
// Asynchronus Code Here
240+
if (/* successfull operation */) {
241+
resolve(/* result */)
242+
} else {
243+
reject(/* reason for failure */)
244+
}
245+
})
246+
```
247+
248+
Inside the `Promise` function, we can perform some asynchronous operations such as making an HTTP request or reading a file from the disk. If the operation succeeds, we can call the `resolve` function with the result of the operation. If the operation fails, we can call the `reject` function with the reason of failure.
249+
250+
Once the `Promise` is created, we can attach one or more `then` methods to ot. The `then` method takes one or two arguments: a function to be called when the `Promise` is resolved, and optionally a fucntion to be called when the `Promise` is rejected.
251+
252+
```js
253+
myPromise
254+
.then((result) => {
255+
// Do something with the result
256+
})
257+
.catch((error) => {
258+
// Handle the error
259+
});
260+
```
261+
262+
When the asynchronous operation completes, the `Promise` is either resolved or rejected. If it's resolved, the function passed to `then` method is called with the result of the operation as its argument. If it is rejected, the function passed to the `catch` method is called with the reason for the failure as its argument.
263+
264+
### `.then()` promise handler
265+
266+
The `.then()` method is used to handle the _fulfilled_ or _rejected_ state of promise. We can think `then` as "_this works and then do this with the data returned from the promise_". It takes two optional arguments: a callback function (result) to be executed when the promise the _fulfilled_, and a callback fucntion (error) to be executed when the promise is _rejected_.
267+
268+
```js
269+
promise.then(
270+
(result) => {
271+
console.log(result);
272+
},
273+
(error) => {
274+
console.log(error);
275+
}
276+
);
277+
```
278+
279+
When a promise is fulfiled, we can access the resolved data by passing just one argument.
280+
281+
```js
282+
promise.then((result) => {
283+
console.log(result);
284+
});
285+
```
286+
287+
When the promise fails and we are interested in only the error, we can pass `null` to the first argument and access the error.
288+
289+
```js
290+
promise.then(null, (error) => {
291+
console.log(error);
292+
});
293+
```
294+
295+
It's bit odd to pass `null` value explicily for an error case so, we have another method `.catch()` for this purpose. We can think of `catch` as "_this does not work so, catch the error so it does not break the code_.
296+
297+
### `.catch()` promise handler
298+
299+
A `catch()` promise handler is a function that is executed when a promise is rejected. It is a method that can be called on a promise object and takes a single argument. As mentioned above, it is a much better syntax to handle the errors than usign the `then()` method.
300+
301+
When a promise is rejected, it will skip the `then()` methods and jump directly to the `catch()` method. The `catch()` handler can be used to handle errors and exceptions that may occur.
302+
303+
```js
304+
promise.then(result => {
305+
// do something with result
306+
}
307+
.catch(error => {
308+
// handle the error
309+
})
310+
)
311+
```
312+
313+
### `.finally()` promise handler
314+
315+
The `finally()` promise handler is a function that is executed regardless of whether a promise is resolved or rejected. It is a method that can be called on promise object and takes no arguments.
316+
317+
The `finally` handler is useful for clean up taks such as resetting state, that needs to be executed regardless of whether the promise is succeessful or not.
318+
319+
```js
320+
const fs = require("fs");
321+
322+
fs.promises
323+
.open("myfile.txt", "r")
324+
.then((file) => {
325+
// do something with the file
326+
})
327+
.catch((error) => {
328+
// handle the error
329+
})
330+
.finally(() => {
331+
// close the file
332+
fs.promises.close(file);
333+
});
334+
```
335+
336+
## ⛓️ Promise Chaining
337+
338+
The promise handlers `then`, `catch` and `finally` helps us to handle any number of asynchronous operations that depend on each other. We can chain the handler methods to pass a value or error from one promise to another.
339+
340+
Promise chaining is a technique used in JavaScript to handle the asynchronous taks in a sequential and organized manner. It involves chaining multiple promises together in specific order to execute a series of asynchronous tasks.
341+
342+
Every promises gives us a `.then()` handler method. Every rejected promise gives us a `.catch()` handler. After creating a promise, we can call the `.then()` method to handle the value.
343+
344+
```js
345+
// Creating a Promise
346+
let promise = new Promise((resolve, reject) => {
347+
resolve("Resolving a Promise.");
348+
});
349+
350+
promise.then((value) => {
351+
console.log(value); // Output: Resolving a Promise.
352+
});
353+
```
354+
355+
We can handle the rejected promise with `.catch()` handler.
356+
357+
```js
358+
// Creating a Promise
359+
let promise = new Promise((resolve, reject) => {
360+
reject(new Error("Rejecting a Promise."));
361+
});
362+
363+
promise.catch((error) => {
364+
console.log(error); // Output: Error: Rejecting a Promise.
365+
});
366+
```
367+
368+
The `.then()` method allows us to handle the result of a Promise once it is completed. There are three main things we can do with the result.
369+
370+
- πŸ’‘ `Return another Promise`: If we need to perform asynchronous operation that depends on the result of the previous `Promise`, we can return another `Promsie` object from the `.then()` method. This allows us to chain multiple Promises together and perform a series of asynchronous operations.
371+
372+
```js
373+
const getUser = new Promise((resolve, reject) => {
374+
const user = {
375+
name: "Lionel Messi",
376+
club: "PSG",
377+
country: "Argentina",
378+
};
379+
resolve(user);
380+
});
381+
382+
getUser
383+
.then((user) => {
384+
console.log("You picked " + user.name + " from " + user.country); // Output: You picked Lionel Messi from Argentina
385+
// Return a new Promise
386+
return new Promise((resolve, reject) => {
387+
setTimeout(() => {
388+
// fetching the rating based on user
389+
resolve(93);
390+
}, 1000);
391+
});
392+
})
393+
.then((rating) => {
394+
console.log("Your player is rated " + rating + ".");
395+
// Output: Your player is rated 93.
396+
});
397+
```
398+
399+
- πŸ’‘`Return a Value`: In some situations, we may not have to make an asynchronous call to get a value. We can simply return a simple value from the `.then()` method rather than returning a promise in these situations.
400+
401+
```js
402+
const getUser = new Promise((resolve, reject) => {
403+
const user = {
404+
name: "Lionel Messi",
405+
club: "PSG",
406+
country: "Argentina",
407+
};
408+
resolve(user);
409+
});
410+
411+
getUser
412+
.then((user) => {
413+
console.log("You picked " + user.name + " from " + user.country); // Output: You picked Lionel Messi from Argentina
414+
// Return a simple value
415+
return user.club;
416+
})
417+
.then((club) => {
418+
console.log("Your player plays for " + club + ".");
419+
// Output: Your player plays for PSG.
420+
});
421+
```
422+
423+
- 🚫 `throw and error`: If there is an error in the Promise chain and we want to stop the execution of the chain, we can throw an error from the `.then()` method. This will cause the Promise chain to skip all remaining `.then()` methods and jump to nearest `.catch()` method to handle error.
424+
425+
```js
426+
const getUser = new Promise((resolve, reject) => {
427+
const user = {
428+
name: "Lionel Messi",
429+
club: "PSG",
430+
country: "Argentina",
431+
position: ["st", "rw", "cam"],
432+
};
433+
resolve(user);
434+
});
435+
436+
getUser
437+
.then((user) => {
438+
console.log("You picked " + user.name + " from " + user.country); // Output: You picked Lionel Messi from Argentina
439+
//Checking the postiton user can play
440+
if (!user.position.includes("def")) {
441+
throw new Error("You player cannot play in defending position.");
442+
}
443+
// Return a simple value
444+
return user.club;
445+
})
446+
.then((club) => {
447+
console.log("Your player plays for " + club + ".");
448+
// Output: Your player plays for PSG.
449+
})
450+
.catch((error) => {
451+
console.log(error);
452+
// Output - Error: You player cannot play in defending position.
453+
});
454+
```
455+
456+
To summarize, the `.then()` method allows us to handle the result of a Promise and perform additional operations based on the result. We can return another promise, a value or throw an error, depending upon the situation.

0 commit comments

Comments
(0)

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /