What Are Promises?
According to MDN - The Promise is object that represents the completion or failure of an asynchronous operation, and its resulting value. The "asynchronous" meaning is that the time when the result will finally came is unknown. Promise can have three following statuses: pending, fulfilled and rejected Example:
function myAsyncFunc(){
return new Promise((reject, resolve) => {
resolve(true);
})
}
To get result of this function you will need to use following syntax:
myAsyncFunc().then(function(result){
console.log(result)
})
Usually promises used to handle asynchronous ajax requests like:
fetch('https://api.github.com/users/angular/repos').then(data=>data.json())
Chaining Promises
What if you need perform some async operations consequentially (one after other)?
For example - to get all repositories of some organization and after get info of the first one?
Well you can use some nested "then" like this:
fetch('https://api.github.com/users/angular/repos')
.then(data=>data.json())
.then(data=>{
fetch('https://api.github.com/repos/angular/angular.js')
.then(repoData=>repoData.json())
.then(repoData=>{
console.log(repoData);
});
})
This will work but code is sprayed on lot of "levels",
More accurate syntax is to return values of each promise result:
fetch('https://api.github.com/users/angular/repos')
.then(data=>data.json())
.then(data=>{
return fetch('https://api.github.com/repos/angular/angular.js')
})
.then(data=>data.json())
.then(repoData=>{
console.log(repoData);
});
Promise.All
Sometimes you need some requests parallel way (all at once).
Angular has for this case $q.all method which receives array of promises and fires callback with arguments for each result of promises list.
Important! results should be ordered in the same order as promises in the array, even if some reults came much later than preceding ones....
Here is my implementation for "promises all"
let all = (promises) => {
//datas is object
let datas={};
//must return promise
return new Promise((resolve, reject)=>{
//runs for each promise
promises.forEach((promise, idx)=>{
promise.then(p => {
datas[idx]=p;//stores results at index property
if(Object.keys(datas).length===promises.length) { //Object.keys(datas).length is indicator that last result received
let res = Object.values(datas);
resolve(res)
}
})
});//foreach
});
}
No comments:
Post a Comment