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
Copy file name to clipboardExpand all lines: README.md
+48-3Lines changed: 48 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -384,7 +384,52 @@ They are generally used with JS's native functions like `map`, `filter`, `reduce
384
384
These are the basics of asynchronous programming in JS. A promise is an object that may produce a single value some time in the future. Either a resolved value or a reason that it's not resolved.
385
385
386
386
```javascript
387
-
var name =prompt("Enter your name");
387
+
functionasyncFunc() {
388
+
constoutput=fetch("result");
388
389
389
-
console.log(name);
390
-
```
390
+
result.then(function(status) {
391
+
console.log("The Status of the output is "+ status);
392
+
});
393
+
}
394
+
```
395
+
396
+
In the above function, the output variables are created later in time, and the result is not available immediately. So, we use promises to handle such cases.
397
+
398
+
Promises can also be written in another way, Promise Object is created and then the `then` method is called on the object.
399
+
400
+
See here, we are using an arrow function to create a promise.
401
+
402
+
```javascript
403
+
functionasyncFunct() {
404
+
returnnewPromise((resolve, reject) => {
405
+
constoutput=fetch("result");
406
+
407
+
if (output) {
408
+
resolve("Success");
409
+
} else {
410
+
reject("Failure");
411
+
}
412
+
});
413
+
}
414
+
415
+
asyncFunct().then((status) => {
416
+
console.log("The status of the output is "+ status);
417
+
});
418
+
```
419
+
420
+
## Async/Await
421
+
422
+
Async and Await are the new way of writing the code asynchronously. It is the same as the promises, but the syntax is different. They have a concept which is called coroutines.
423
+
424
+
Coroutine is a function, which will wait until the function is run, and return the control to the main loop, once the event occurred then the function will be resumed.
425
+
426
+
The `await` is a special keyword that tells the JS to wait until the promise is returned. It can resolve or reject depending on the promise. And await keyword can only be used inside async function. `async` functions only return a promise, they don't return the actual value. To get the actual value, we need to `await` for the `async` function. The syntax for the `async` function is given below.
427
+
428
+
```javascript
429
+
asyncfunctionasyncFunc() {
430
+
constoutput=awaitfetch("result");
431
+
return output;
432
+
}
433
+
```
434
+
435
+
The `async` function implicitly returns a promise, so we can use the `then` method to get the value later.
0 commit comments