admin管理员组

文章数量:1400424

I have a function that runs a query (returning a promise) and then manipulates the returned data. How do I get the calling function to have access to the manipulated data?

The call is like this:

getAgeGroupList().then(function (result) {
        // Would like to access manipulated data here.
    });

And the function is as below. The query.find() returns a Promise in Parse.

function getAgeGroupList(){
    var query = new Parse.Query("Fixtures_and_results");
    return query.find({
        success: function(results) {
             /* Manipulate results here, then return manipulated data */
             // How do I return the manipulated data? e.g return(newArray)
        },
        error: function(error) {  
        }
    });
}

I have a function that runs a query (returning a promise) and then manipulates the returned data. How do I get the calling function to have access to the manipulated data?

The call is like this:

getAgeGroupList().then(function (result) {
        // Would like to access manipulated data here.
    });

And the function is as below. The query.find() returns a Promise in Parse.

function getAgeGroupList(){
    var query = new Parse.Query("Fixtures_and_results");
    return query.find({
        success: function(results) {
             /* Manipulate results here, then return manipulated data */
             // How do I return the manipulated data? e.g return(newArray)
        },
        error: function(error) {  
        }
    });
}
Share Improve this question asked Apr 27, 2018 at 16:19 SimpleOneSimpleOne 1,0863 gold badges14 silver badges32 bronze badges 1
  • You would need to return the promise from getAgeGroupList() and then resolve the promise in your success function. – entropic Commented Apr 27, 2018 at 16:21
Add a ment  | 

1 Answer 1

Reset to default 6

If query.find returns a promise, then you don't want to use success and error handlers; instead, use then to manipulate the value:

function getAgeGroupList(){
    var query = new Parse.Query("Fixtures_and_results");
    return query.find().then(results => {
        // Manipulate results here
        return updatedResults;
    });
}

That will return a new promise that will resolve with your manipulated results rather than the original. This is promise chaining.

If the query.find call fails, its promise will reject, and the promise created by then will pass that rejection along (without calling the then handler).


I used an arrow function above, but looking at your code, it doesn't use any ES2015+ features other than promises. So you may want:

function getAgeGroupList(){
    var query = new Parse.Query("Fixtures_and_results");
    return query.find().then(function(results) { // <=== Changed to traditional function
        // Manipulate results here
        return updatedResults;
    });
}

instead.

本文标签: javascriptParse Promise return a valueStack Overflow