As we have seen earlier, With asynchronous programming, JavaScript programs can start long-running tasks, and continue running other tasks in parallel.
But, asynchronus programmes are difficult to write and difficult to debug.
Because of this, most modern asynchronous JavaScript methods don't use callbacks. Instead, in JavaScript, asynchronous programming is solved using Promises instead.
A Promise contains both the producing code and calls to the consuming code:
Promise Syntax:
let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)
myResolve(); // when successful
myReject(); // when error
});
// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
When the producing code obtains the result, it should call one of the two callbacks:
When Call
Success myResolve(result value)
Error myReject(error object)
Promise Object Properties:
A JavaScript Promise object can be:
Pending
Fulfilled
Rejected
The Promise object supports two properties: state and result.
While a Promise object is "pending" (working), the result is undefined.
When a Promise object is "fulfilled", the result is a value.
When a Promise object is "rejected", the result is an error object.
myPromise.state myPromise.result
"pending" undefined
"fulfilled" a result value
"rejected" an error object
Let us understand the use of Promise with an example:
function displayValue(some) {
console.log('Inside displayValue');
}
let myPromise = new Promise(function(myResolve, myReject) {
let x = 0;
// The producing code (this may take some time)
if (x == 0) {
myResolve("OK");
} else {
myReject("Error");
}
});
myPromise.then(
function(value) {displayValue(value);},
function(error) {displayValue(error);}
);
Output:
Inside displayValue
Let us understand the use of Promise with setTimeout.
Example Using Callback:
setTimeout( myFunction, 1000);
function myFunction() {
console.log('Inside myFunction');
}
Output:
Inside myFunction
Example Using Promise:
function myFunction(some) {
console.log('Inside myFunction');
}
let myPromise = new Promise(function(myResolve, myReject) {
let x = 1;
if (x == 1) {
myResolve("OK");
console.log('Inside If');
setTimeout(myFunction , 3000);
} else {
console.log('Inside else');
myReject("Error");
}
});
myPromise.then(
function(value) {
console.log('Inside Value');
myFunction(value);},
function(error) {
console.log('Inside Error');
myFunction(error);}
);
Output:
Inside If Inside Value Inside myFunction
No comments:
Post a Comment