promise object is data returned by asynchronous function. It can be a resolve if the function returned successfully or a reject if function returned an error.
Promise: In JavaScript
JavaScript is single-threaded. Everything happens in the sequence it is written, line-by-line. But, asynchronous operations occur in the order they complete.
how you create a promise in JavaScript:
var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
The promise constructor takes in one argument: a callback function with two parameters — resolve and reject.
This promise can then be used like this:
promise.then(function(result) {
console.log("Promise worked");
}, function(err) {
console.log("Something broke");
});
If promise was successful, a resolve will happen and the console will log Promise worked, otherwiseSomething broke. That state between resolve and reject where a response hasn’t been received is pending state.
In short, there are 3 states to a promise:
- pending: awaiting promise response
- resolve : promise has successfully returned
- reject: failure occurred
Example1 : Using XMLHttpRequest object to make API Call
To fully understand the concept of promises, lets create an app which loads an image. If image is loaded, we will display the image, or else log an error.
First, lets create a promise using XMLHttpRequest(XHR).
// Import stylesheets
import './style.css';
// Write Javascript code!
const appDiv = document.getElementById('app');
const loadImage = function(url) {
return new Promise(function(resolve, reject) {
//Open a new XHR
var request = new XMLHttpRequest();
request.open('GET', url);
// When the request loads, check whether it was successful
request.onload = function() {
if (request.status === 200) {
// If successful, resolve the promise
resolve(request.response);
} else {
// Otherwise, reject the promise
reject(Error('An error occurred while loading image. error code:' + request.statusText));
}
};
request.send();
});
};
const embedImage = () => {
loadImage('https://jsonplaceholder.typicode.com/todos/1').then(function(result) {
appDiv.innerHTML = result;
},
function(err) {
appDiv.innerHTML = err;
console.log(err);
});
}
embedImage();
Example : Using Promise in javascript function call
cal = function(x,y) {
console.log("x = " + x, "y = " + y);
positiveSum(x,y).then(result => {
console.log("sum = " + result);
}).catch(err => {
console.log(err)
console.log("end of function");
})
}
positive = function(x,y) {
return new Promise(function (resolve, reject) {
if(x+y > 0){
resolve(x+y)
} else {
reject("Sum is less than zero")
}
})
}
cal(2,9)
Example 2 : Using Then Catch method to make API call
const getData = () => {
return new Promise((res,rej)=>{
fetch("https://jsonplaceholder.typicode.com/todos/1")
//.then(response => response.json())
.then(response => { return response.json()})
.then(json => res(json.title));
});
};
getData()
.then (resultProm => console.log(resultProm)) // delectus aum
Example 3 : Using Async/await
//A function return a promise
const getData = () => {
return new Promise((resolve,rej)=>{
fetch("https://jsonplaceholder.typicode.com/todos/1")
//.then(response => response.json())
.then(response => { return response.json()})
.then(json => resolve(json.title));
});
};
//Using Then Catch method
getData()
.then (resultProm => console.log(resultProm)) // delectus aum
//Using Async/Await method
var resultStr = '';
var main = async()=>{
resultStr = await getData();
console.log('resultStr : ', resultStr)
}
main()
<div id="app"></div>
Promise Reference
- Chain JS Promise
- Promise Chain
- Mozila Promise
- Understanding JS Promise
- Promise Org
- Mastering Promise Angular2
- Promise Angular2 Youtube
- Promise VS RXJs Observable
- Promise Vs Observable Stack
- Promise For Asynchronous Programming
- Mastering Asynchronous
- Callback Vs Promise Vs Async await SitePoint
- Using Promise With Mongoose
- Switching Out Callback in Mongoose
- Nodejs Promise
- JS Promise and Error
- Codeburst
- Angular Promise DotnetGuru
- Promise instead of Callback in Mongoose
- Counting Promise Vs Rx