You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This is the old-fashioned classical approach to asynchronous programming. You provide a function as an argument to another function that executes an asynchronous task. When the asynchronous task completes, the executing function calls your callback function.
74
+
72
75
A callback function is a function passed into another function as an argument,
73
76
which is then invoked inside the outer function to complete some kind of action.
74
77
It is also known as Higher-order Function.
@@ -82,23 +85,62 @@ pair of executing parenthesis () like we do when we are executing a function.
82
85
83
86
Callback functions Are **Closures.** Callback function is executed inside the containing function’s body just as if
84
87
the callback were defined in the containing function. Hence callback function has access to the function variables as
85
-
well as global variables.
88
+
well as global variables.
89
+
90
+
The disadvantage of using callback occurs when you have multiple chained async tasks, which requires you to define callback inside callback, inside callback and that result in **callback hell**
Promises have been introduced in ES6 (2015) to allow for more readable asynchronous code than is possible with callbacks.
99
+
93
100
The promise constructor takes one argument, a callback with two parameters, resolve and reject.
94
101
Do something within the callback, perhaps async, then call resolve if everything worked, otherwise call reject.
95
102
103
+
The main difference between callbacks and promises is that with callbacks you tell the executing function
104
+
what to do when the asynchronous task completes, whereas with promises the executing function returns a special
105
+
object to you (the promise) and then you tell the promise what to do when the asynchronous task completes.
106
+
96
107
A Promise can be:
97
108
1. fulfilled - The action relating to the promise succeeded
98
109
2. rejected - The action relating to the promise failed
99
110
3. pending - Hasn't fulfilled or rejected yet
100
111
4. settled - Has fulfilled or rejected
101
112
113
+
```javascript
114
+
let promise =newPromise(function(resolve, reject) {
115
+
resolve(1);
116
+
});
117
+
118
+
promise.then(data=>console.log(data));
119
+
```
120
+
121
+
122
+
<aname=“async”/>
123
+
124
+
#### Async/ Await
125
+
126
+
Async/await has been introduced in ES8 (2017). This technique should really be listed under promises, because it is just syntactic sugar for working with promises. However, it is a syntactic sugar that is really worth looking at.
127
+
128
+
```javascript
129
+
asyncfunctionf() {
130
+
try {
131
+
let response =awaitfetch('https://jsonplaceholder.typicode.com/posts');
0 commit comments