Use of Promise in ES6
Posted By : Dinesh Kumar | 12-Dec-2018
When you execute an assignment synchronously, you trust that it will complete before proceeding onward to the following line of code.
When you execute an assignment asynchronously, the program moves to the following line of code before the errand wraps up.
Consider synchronous programmings like holding up in line and nonconcurrent programming like taking a ticket. When you take a ticket you can go do different things and afterward be advised when prepared.
Callbacks
One approach to program asynchronously is to use callbacks. We go to a nonconcurrent function a function which it will consider when the undertaking is finished.
function doAsyncTask(cb) {
setTimeout(() => {
console.log("Async Task Calling Callback");
cb();
}, 1000);
}
The doAsyncTask function when called kicks of a nonconcurrent assignment and returns quickly.
To get told when the async errand finishes we go to doAsyncTask a function which it will consider when the undertaking finishes.
It's known as a callback function, CB for short because it gets back to you.
Promise API
In ES6 we have an elective instrument incorporated with the dialect called a promise.
A promise is a placeholder for future esteem.
It serves indistinguishable function from callbacks however has a more pleasant language structure and makes it less demanding to deal with mistakes.
Making a Promise
We make an instance of a promise by calling new on the Promise class, as so:
var promise = new Promise((resolve, dismiss) => {
});
We go to Promise an internal function that takes two contentions (resolve, dismiss).
Since we are characterizing the function we can consider these contentions whatever we need yet the tradition is to call them to resolve and reject.
resolve and reject are in actuality functions themselves.
Inside this inward function, we play out our offbeat preparing and after that when we are prepared we call resolve(), like so:
var promise = new Promise((resolve, dismiss) => {
setTimeout(() => {
console.log("Async Work Complete");
resolve();
}, 1000);
});
We, as a rule, restore this promise from a function, as so:
function doAsyncTask() {
var promise = new Promise((resolve, dismiss) => {
setTimeout(() => {
console.log("Async Work Complete");
resolve();
}, 1000);
});
return promise;
}
On the off chance that there was a mistake in the async errand, we call the reject() function like so:
function doAsyncTask() {
var promise = new Promise((resolve, dismiss) => {
setTimeout(() => {
console.log("Async Work Complete");
in the event that (blunder) {
dismiss();
} else {
resolve();
}
}, 1000);
});
return promise;
}
Promise Notifications
We can get advised when a promise resolves by joining a win handler to it's at that point function, as so:
doAsyncTask().then(() => console.log("Task Complete!"));
at that point can take two contentions, the second contention is a mistake handler that gets called if the promise is rejected, as so:
doAsyncTask().then(
() => console.log("Task Complete!"),
() => console.log("Task Errored!"),
);
Any qualities we go to the resolve and reject functions are passed along to the blunder and achievement handlers, as so:
let mistake = genuine;
function doAsyncTask() {
return new Promise((resolve, dismiss) => {
setTimeout(() => {
in the event that (blunder) {
reject('error');/pass esteems
} else {
resolve('done');/pass esteems
}
}, 1000);
});
}
doAsyncTask().then(
(val) => console.log(val),
(blunder) => console.error(err)
);
Prompt Resolution or Rejection
We can make a quickly resolved Promise by utilizing the Promise.resolve() strategy, as so:
let promise = Promise.resolve('done');
What's more, a promptly dismissed Promise by utilizing the Promise.reject() strategy, as so:
let promise = Promise.reject('fail');
A pleasant aspect concerning Promises is that in the event that we include a handler after the guarantee resolves or rejects the handler still gets called.
let promise = Promise.resolve('done');
promise.then((val) => console.log(val));//'done'
In the above model, despite the fact that the Promise has resolved before we included the achievement handler, the promise system still calls the achievement handler.
Fastening
We can likewise interface a progression of then handlers together in a chain, as so:
Promise.resolve("done")
.at that point(
(val) => {
console.log(val);
return 'done2';
},
(blunder) => console.error(err)
)
.at that point(
(val) => console.log(val),
(blunder) => console.error(err)
);
//'done'
//'done2'
Promises pass a blunder along the chain until it finds a mistake handler. So we don't have to characterize a mistake handler for every at that point function, we can simply include one toward the end like so:
Promise.reject('fail')
.then((val) => console.log(val))
.at that point(
(val) => console.log(val),
(fail) => console.error(err)
);
On the off chance that we toss a special case from our promise function or one of the achievement handlers, the promise gets rejected and the mistake handler is called, as so:
Promise.resolve('done')
.then((val) => {
toss new Error("fail")
})
.at that point(
(val) => console.log(val),
(fail) => console.error(err)
);
//[Error: fail]
Catch
The catch function works the very same path as the then mistake handler, it's simply clearer and all the more expressly portrays our purpose to deal with blunders.
Promise.resolve('done')
.then((val) => {throw new Error("fail")})
.then((val) => console.log(val))
.catch((err) => console.error(err));
Outline
Promises are a far cleaner answer for composing offbeat code than callbacks.
The subsequent code that is made is less demanding to peruse and is frequently composed the request the application will execute.
So it tends to be less demanding to follow through the code in your mind.
With the catch handler, it additionally gives us a solitary place where we can deal with mistakes.
Posting
Posting 1. script.js
'use strict';
//Via callbacks
/*
function doAsyncTask(cb) {
setTimeout(() => {
console.log("Async Task Calling Callback");
cb();
}, 1000);
}
doAsyncTask(() => console.log("Callback Called"));
*/
//Via Promise
let mistake = false;
function doAsyncTask() {
return new Promise((resolve, dismiss) => {
setTimeout(() => {
on the off chance that (blunder) {
reject('error');
} else {
resolve('done');
}
}, 1000);
});
}
doAsyncTask().then(
(val) => console.log(val),
(fail) => console.error(err)
);
//Immediately Resolved Promise
let promise = Promise.resolve('done');
promise.then((val) => console.log(val));//'done'
//Handling Errors
Promise.resolve('done')
.then((val) => {throw new Error("fail")})
.then((val) => console.log(val))
.catch((err) => console.error(err));
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Dinesh Kumar
Dinesh Kumar is an experienced with knowledge of Spring Framework, Spring Boot, Java, Javascript, JQuery, AngularJs, and SQL.