-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcallback-&-promisses.js
More file actions
349 lines (275 loc) · 10.4 KB
/
callback-&-promisses.js
File metadata and controls
349 lines (275 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/*
callback =>
callback is a function passes as argument as a another function.A Callback would be helpful in events.
ex=>
function fun(a, b, callback) {
console.log(a + b);
callback();
}
//callback function
function callme() {
console.log("addtion sucsesss and i am call back");
}
fun(3, 4, callme);
The following example will help us better understand this concept.
function notifyAll(fnSms, fnEmail) {
console.log('starting notification process');
fnSms();
fnEmail();
}
notifyAll(function () {
console.log("Sms send ..");
}, function () {
console.log("email send ..");
});
console.log("End of script"); //executes last or blocked by other methods
In the code mentioned above, the function calls are synchronous.It means the UI thread
would be waiting to complete the entire notification process.Synchronous calls become
blocking calls.To enable the script, execute an asynchronous or a non - blocking call to notifyAll() method.We shall use the setTimeout() method of JavaScript.This method is async by default.
function notifyAll(fnSms, fnEmail) {
setTimeout(function () {
console.log('starting notification process');
fnSms();
fnEmail();
}, 2000);
}
notifyAll(function () {
console.log("Sms send ..");
},
function () {
console.log("email send ..");
});
console.log("End of script");
PROMISSES =>
Promise is an Object represent eventual compeletion or falure of an asynchronous operation
JavaScript Promise are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.Prior to promises events and callback functions were used but they had limited functionalities and created unmanageable code.Multiple callback functions would create callback hell that leads to unmanageable code.Promises are used to handle asynchronous operations in JavaScript.
Syntax:
let promise = new Promise(function (resolve, reject) {
//do something
});
parameter =>
promises constructor takes only argument which is call back function
callback function takes tow argument resove, reject
1) resolve =>
Perform operations inside the callback function and if everything went well then call resolve.
2) reject =>
If desired operations do not go well then call reject.
promise has four state =>
1) fulfilled:=> Action related to the promise succeeded
2) rejected:=> Action related to the promise failed
3) pending:=> Promise is still pending i.e.not fulfilled or rejected yet
4) settled:=> Promise has been fulfilled or rejected
Promises can be consumed by registering functions using.then and.catch methods.
1. Promise then() Method:=> It is invoked when a promise is either resolved or rejected.It may also be defined as a carrier that takes data from promise and further executes it successfully.
2. Promise catch () Method:=> It is invoked when a promise is either rejected or some error has occurred in execution.It is used as an Error Handler whenever at any step there is a chance of getting an error.
Parameters: It takes one function as a parameter.
example=>
const promise = new Promise((resolve, reject) => {
let value = true
if (value) {
resolve('hey value is true')
} else {
reject('there was an error, value is false')
}
})
promise
.then((x) => {
console.log(x)
})
.catch((err) => console.log(err))
Asynchronous example =>
var user = false;
function getUsers() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (user) {
resolve([
{ name: "aamir", pass: "amir@123" },
{ name2: "ali", pass2: "ali" }
]);
}
else {
reject("user is rejected")
}
}, 2000);
});
}
let prom = getUsers();
prom.then((data) => {
console.log(data);
}).catch((data) => {
console.log(data);
})
promiesse method =>
Let’s say we want many promises to execute in parallel and wait until all of them are ready.
For instance, download several URLs in parallel and process the content once they are all done.The Promise.all() static method takes an iterable of promises:
That’s what Promise.all is for.
The syntax is:
let promise = Promise.all(iterable);
The Promise.all() method returns a single promise that resolves when all the input promises have been resolved.
Example1=> (Resolve)
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("first promis resolve");
resolve(10);
}, 1 * 1000);
})
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("seceond promise resolve");
resolve(20);
});
});
Promise.all([p1, p2]).then((result) => {
const add = result.reduce((p, c) => {
return p + c;
});
console.log("result is" + result);
console.log(add);
})
Example2(rejected)=>
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('The first promise has resolved');
resolve(10);
}, 1 * 1000);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('The second promise has rejected');
reject('Failed');
}, 2 * 1000);
});
const p3 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('The third promise has resolved');
resolve(30);
}, 3 * 1000);
});
Promise.all([p1, p2, p3]).then((result) => {
console.log(result);
}).catch((Error) => {
console.error(Error);
})
promise.race()=>
Similar to Promise.all, but waits only for the first settled promise and gets its result(or error).
The syntax is:
let promise = Promise.race(iterable);
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
// console.log('The first promise has resolved');
resolve(10);
}, 1000);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
// console.log('The second promise has rejected');
reject('Failed');
}, 1000);
});
const p3 = new Promise((resolve, reject) => {
setTimeout(() => {
// console.log('The third promise has resolved');
resolve(30);
}, 1000);
});
Promise.race([p1, p2, p3]).then((result) => {
console.log(result);
}).catch((error) => {
console.log(error);
})
promise.any()=>
The Promise.any() method accepts a list of Promise objects as an iterable object:
Promise.any(iterable);
Code language: JavaScript (javascript)
If one of the promises in the iterable object is fulfilled, the Promise.any() returns a single promise that resolves to a value which is the result of the fulfilled promise:
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Promise 1 rejected');
reject('error');
}, 1000);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Promise 2 fulfilled');
resolve(2);
}, 2000);
});
const p = Promise.any([p1, p2]);
p.then((value) => {
console.log('Returned Promise');
console.log(value);
});
Introduction to the Promise.allSettled() method=>
ES2020 introduced the Promise.allSettled() method that accepts a list of Promises and returns a new promise that resolves after all the input promises have settled, either resolved or rejected.
The following shows the syntax of the Promise.allSettled() method:
const p1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('The first promise has resolved');
resolve(10);
}, 1 * 1000);
});
const p2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('The second promise has rejected');
reject(20);
}, 2 * 1000);
});
Promise.allSettled([p1, p2])
.then((result) => {
console.log(result);
});
Async and Await keyword=>
ES2017 introduced the async/await keywords that build on top of promises, allowing you to write asynchronous code that looks more like synchronous code and is more readable. Technically speaking, the async / await is syntactic sugar for promises.
If a function returns a Promise, you can place the await keyword in front of the function call, like this:
let result = await f();
Code language: JavaScript (javascript)
The await will wait for the Promise returned from the f() to settle. The await keyword can be used only inside the async functions.
Example=> function getUser(userId) {
return new Promise((resolve, reject) => {
console.log('Get user from the database.');
setTimeout(() => {
resolve({
userId: userId,
username: 'john'
});
}, 1000);
})
}
function getServices(user) {
return new Promise((resolve, reject) => {
console.log(`Get services of ${user.username} from the API.`);
setTimeout(() => {
resolve(['Email', 'VPN', 'CDN']);
}, 2 * 1000);
});
}
function getServiceCost(services) {
return new Promise((resolve, reject) => {
console.log(`Calculate service costs of ${services}.`);
setTimeout(() => {
resolve(services.length * 100);
}, 3 * 1000);
});
}
async function showServiceCost() {
let user = await getUser(100);
let services = await getServices(user);
let cost = await getServiceCost(services);
console.log(`The service cost is ${cost}`);
}
showServiceCost();
The async keyword=>
The async keyword allows you to define a function that handles asynchronous operations.
To define an async function, you place the async keyword in front of the function keyword as follows:
async function sayHi() {
return 'Hi';
}
Asynchronous functions execute asynchronously via the event loop. It always returns a Promise.
The await keyword=>
You use the await keyword to wait for a Promise to settle either in resolved or rejected state. And you can use the await keyword only inside an async function:
async function display() {
let result = await sayHi();
console.log(result);
}
*/