简体   繁体   English

解析Promise返回值

[英]Parse Promise return a value

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. query.find()返回一个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) {  
        }
    });
}

If query.find returns a promise, then you don't want to use success and error handlers; 如果query.find返回一个promise,那么您就不想使用successerror处理程序; instead, use then to manipulate the value: 而是使用then来操纵值:

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). 如果query.find调用失败,则其诺言将被拒绝, then创建的诺言将传递该拒绝(不调用then处理程序)。


I used an arrow function above, but looking at your code, it doesn't use any ES2015+ features other than promises. 我在上面使用了箭头功能,但在您的代码中,它除了promise外没有使用任何ES2015 +功能。 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. 代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM