What is asynchronous and synchronous.
A simple definition of asynchronous and synchronous is, the execution of functions statement by statement i.e the next statement will get executed only after the execution of the previous statement, this property is defined as synchronous property. Vise Versa is asynchronous property i.e the next statements may or may not(depending on the time of execution ) wait for the execution of the previous statement.
How to handle the asynchronous property of javascript?
Present there were many methods and processes to handle the asynchronous property of javascript based on the condition. We will discuss a few of them which are important and we use most.
To start from the history the first thing that was introduced to handle the asynchronous property of javascript is Callbacks. All the methods that came after including the callbacks internally and reduces the coding time.
Callbacks
It includes the process of passing a function call as a parameter to another function. For example, I’m having a function which will get the data from the server API and I need to print the “Data driven successfully” only after the execution of getting data from the API here will need to use callbacks to handle the asynchronous property
function one (apioptions,callback){
let res = rrequest(apioptions)
if(res){
callback();
}
}
one({url:” http://localhost:3000”, method:”GET”}, () = >{
console.log(“ Data driven successfully ”);
})
Promises
A Promise constructor is used to evaluate asynchronous code in a synchronous way. A Promise is a proxy for a value
Syntax:
new Promise(executor);
It is a function that is passed with the arguments resolve and reject. The executor calls some asynchronous function, and then, once that completes, either calls the resolve function to resolve the promise or rejects it if an error occurred. If it throws an error, the promise is rejected. The return value of the executor is ignored.
A Promise is in one of these three states.
- Pending
- Fulfilled
- Rejected
A pending promise can be either fulfilled or rejected for a reason.
Below is the syntax for Promise object :
Example :
let promise = new Promise(function(resolve, reject);
resolve(value) : it returns a promise successfully
reject(error) : it indicates an error in a Promise
Properties :
Promise.length is always 1.
Methods :
There are 4 static methods in the Promise.
1. Promise.resolve() :
It returns a resolved promise with the given value.
Example :
let promise = new Promise(resolve => {
setTimeout(() => resolve("done!"), 1000);
});
promise.then(console.log()); //returns “done!”
2. Promise.reject() :
It returns a rejected promise with the error.
Example :
let promise = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error(“error”)), 1000);
});
promise.catch(console.log()); // shows “Error: error” after 1 second
3. Promise.all() :
It takes an array of promises and returns a new promise. The new promise resolves when all the listed promises are resolved and have an array of their results.
Example :
Promise.all([
new Promise(resolve => setTimeout(() => resolve(1), 3000)), // 1
new Promise(resolve => setTimeout(() => resolve(2), 2000)), // 2
new Promise(resolve => setTimeout(() => resolve(3), 1000)) // 3
]).then(
console.log(.....);
);
Or
Promise.all([
new Promise((resolve, reject) => {setTimeout(() => resolve(1), 1000)}),
2, // treated as Promise.resolve(2)
3 // treated as Promise.resolve(3)
]).then(console.log(.....)); // 1, 2, 3
it gives a result as [1,2,3]
Another example for having an array of URLs in a code,
Example :
let urls = [
'https://api.github.com/users/iliakan',
'https://api.github.com/users/remy',
'https://api.github.com/users/jeresig'
];
let req = urls.map(url => fetch(url));
// Promise.all waits until all are resolved
Promise.all(req).then(responses =>
responses.forEach(response =>
console.log(response);));
If any of the promises is rejected, Promise.all immediately rejects with that error.
Example :
Promise.all([
new Promise((resolve, reject) => setTimeout(() => resolve(1), 1000)),
new Promise((resolve, reject) => setTimeout(() => reject(new Error(“error”)), 2000)),
new Promise((resolve, reject) => setTimeout(() => resolve(3), 3000))
]).catch(console.log(err)); // Error: error
4. Promise.race() :
It returns a promise that resolves as one of the arrays of iterable with that value or rejection. It is similar to Promise.all and takes an array of iterables.
Example :
let p1 = new Promise((res, rej) => { setTimeout(res, 100, 'foo') });
let p2 = new Promise((res, rej) => { setTimeout(res, 200, 'bar') });
race(p1, p2).then(a => console.log(a)); // "foo"
let p3 = new Promise((res, rej) => { setTimeout(rej, 50, 'baz') });
race(p1, p2, p3).then(a => console.log(a))
.catch(e => console.log(e)); // "baz"
Note: p3 will be executed first because timeout for p3 is lesser than p1 and p2. It returns only p3 that will be either rejected or resolved.
And we have a promise with callbacks that return the values of the execution.
return new Promise (resolve,reject, (err, res)=>{
if(err) {
reject(err)
} else {
resolve(res)
}
}).catch(err)
Async/Await
Async/Await is a new syntax for writing asynchronous code in JavaScript to make asynchronous code behave in a synchronous way.
The word async is used before a function that means a function always returns a promise. If a function returns a non-promise value, the function with async keyword returns like a resolved promise.
Ex: async function () {
return 1;
}
Await is another keyword, that works only inside async functions. It makes JavaScript wait until that promise settles and returns its result.
Example 1:
let value=await Promise();
Example 2:
async function () {
// waits for 1 second, then result becomes 2
let result = await getResult();
console.log(result);
}
getResult(){
return 2;
}
Example 3:
async wait() {
return await Promise.resolve(1);
}
If a promise resolves, it returns a value. But if a promise returns a rejection, it throws an error.
Example 4:
async function () {
await Promise.reject(new Error("error"));
}
In this error case, we can use try/catch to catch that error.
Example 5:
try {
let response = await fetch('/no-name');
let user = await response.json();
} catch(err) {
console.log(err);
}
Using .then/catch for getting a response from url
Example 6:
return fetch(api)
.then(response => {
if (response) {
return response;
}
}).catch((err)=>{
console.log(err);
});
Most of the cases we are using async-await and promises with a callback. AsyncAwait uses in local coding, but when trying to get the form an external API we will use promises with a callback.