How to return a Promise from the resolution of others?

Asked

Viewed 118 times

2

I’m relatively new to this Promises, despite having used them numerous times, especially in AJAX requests.

I’m building a front-end application that runs on Sharepoint and, to get a lot of information about the user by accessing the page, I need to make 2 different requests to the Sharepoint API, since a URL just doesn’t provide all the data I need.

To make it easier, I’m creating a lib with several methods for consuming the API to make it easier to reuse logic in several projects. Thus, I wanted to summarize the two requests for user data in a single function, already merging the results and returning a single object.

I see that the Promise.all() does this role of expecting multiple files and returning a single new file, but the result is an array, and wanted them to be the merged object resulting from the 2 files.

And to make it a little harder, I need to make a lib compatible with IE, which eliminates the possibility of using the Async/Await approach.

Here’s what I got:

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);
});

1 answer

1


I studied the files a little better and I was able to realize the solution: encapsulate all the content in a new file and call the solution within Promise.all(), when the results have already passed 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);
            });
    });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.