Skip to content

Commit 13cf82b

Browse files
committed
added promise and async and await
1 parent 65520ee commit 13cf82b

File tree

1 file changed

+48
-3
lines changed

1 file changed

+48
-3
lines changed

README.md

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -384,7 +384,52 @@ They are generally used with JS's native functions like `map`, `filter`, `reduce
384384
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.
385385

386386
```javascript
387-
var name = prompt("Enter your name");
387+
function asyncFunc() {
388+
const output = fetch("result");
388389

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+
function asyncFunct() {
404+
return new Promise((resolve, reject) => {
405+
const output = 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+
async function asyncFunc() {
430+
const output = await fetch("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

Comments
 (0)