In this tutorial, you’ll learn how to return data from JavaScript Promise. Assuming that you have a basic understanding about JavaScript Promises, I’ll start by creating a method which returns a Promise, so that you can see how to return data from promise.
function getPromise(){
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve({'country' : 'INDIA'});
},2000)
})
}
The above method returns a promise which when resolved produces a JSON object. Let’s make a call to the above method and return its result.
function getPromise() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({
'country': 'INDIA'
});
}, 2000)
})
}
function getResult() {
getPromise()
.then(function(response) {
return response;
})
}
let result = getResult();
console.log(result);
As seen in the above code, getResult methods makes a call to the getPromise method and once resolved it returns the response. If you try running the above code, the result logged will be undefined. This happens because after making a call to getResult method, it in turns calls the getPromise method which gets resolved only after 2000 ms. getResult method doesn’t wait since it doesn’t returns a promise.
So, if you return a promise from getResult method it can then be used to wait for the Promise to get resolved. Let’s try it.
function getResult() {
return getPromise()
.then(function(response) {
return response;
})
}
getResult()
.then(function(result) {
console.log(result);
})
Now you are able to return data from JavaScript promise.
Return Data From Promise using ES6 Async/Await
JavaScript ES6 provides a new feature called async/await which can used as an alternative to Promise.then. Using async/await you can write the above code in synchronous manner without any .then.
function getPromise(){
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve({'country' : 'INDIA'});
},2000)
})
}
async function getResult(){
let result = await getPromise();
return result
}
async function doTask(){
let data = await getResult();
console.log(data)
}
doTask();