I'm just a beginner with JavaScript Promises, although I have extensively used them in my life, with AJAX requests.
I am building a front-end application to run from SharePoint library and it requests user info from SharePoint API to customize the page content. To get all the information I want, I need to fetch 2 different URL, since one does not contain all the data I seek.
Besides, I am building a lib to facilitate the consumption of SharePoint API and I wish these 2 promises were resolved in a single one, with the results in both already merged in a single JSON userData
. I know Promise.all()
does something similar, however its result is an array with separate result, which does not meet the second part I want...
Also, keep in mind that I am building an application fully compatible with IE, so many resources like Asyn/Await are discarded.
So I wanted the function getUser()
below already to return a promise with the merged object properties:
function getUser() {
var userData1 = axios.get(url + '/web/CurrentUser');
var userData2 = axios.get(url + '/SP.UserProfiles.PeopleManager/GetMyProperties');
return Promise.all([userData1, userData2]);
}
var userDataAll;
getUser().then(function(values) {
userDataAll = Object.assign({}, values[0].data, values[1].data);
});
I got it! I understood the way promises work and found the solution myself: all I needed is to encapsulate the steps into a new promise and call the resolve()
callback once Promise.all()
is resolved and the merge ended with the Object.assign()
:
function getUser() {
return new Promise(function(resolve, reject) {
var userData1 = axios.get(url + '/web/CurrentUser');
var userData2 = axios.get(url + '/SP.UserProfiles.PeopleManager/GetMyProperties');
Promise
.all([userData1, userData2])
.then(function(results) {
let userData = Object.assign({}, results[0].data, results[1].data);
resolve(userData);
})
.catch(function(errors) {
reject(errors);
});
});
}