解析云代码承诺存在的问题 [英] Issues with Parse Cloud Code Promises

查看:122
本文介绍了解析云代码承诺存在的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Parse Cloud Code,并使用Promise来确保消除因Cals异步引起的任何问题.我想查询一个类,找回一个对象,建立一些JSON,然后查询该对象的一些关系(标签,裁判),并将它们添加到JSON中以返回ExpressJS进行渲染.我粘贴的代码无法正常工作,但是我不明白为什么每次我返回项目时都要查询下一个承诺.

I am trying to work with Parse Cloud Code and use promises to make sure I eliminate any issues with cals being async. I am wanting to query a class, get an object back, build up some JSON, then query some relations of the object (tags, referees) and add them to the JSON to return back for ExpressJS to render. The code I paste is not working but I don't understand why if each time I am returning to project for the next promise to query on.

//Return a single project
Parse.Cloud.define('getProject', function(request, response) {
    var projectUrl = request.params.projectUrl;

    var project;
    var projectsData = [];

    var Projects = new Parse.Object("projects");
    var query = new Parse.Query(Projects);
    query.equalTo("projectUrl", projectUrl);
    query.find().then(function(projectsResult) {
        console.log(projectsResult.length + " Projects returned");

        project = projectsResult[0];
        var projectData = {
            "id": project.get("id"),
            "title": project.get("title"),
            "previewImage": project.get("previewImage"),
            "longDescription": project.get("longDescription"),
            "shortDescription": project.get("shortDescription"),
            "visibleToPublic": project.get("visibleToPublic"),
            "dateStart": project.get("dateStart"),
            "dateEnd": project.get("dateEnd"),
            updatedAt: project.get("updatedAt"),
            projectStatus: project.get("projectStatus")
        };

        projectsData.push(projectData);
        console.log("Step 1. Projects Data: " + JSON.stringify(projectsData));

        var tagsQuery = project.relation('tags');
        return tagsQuery.query().find();
    }).then(function(tags) {
        var tagsData = [];
        for(var t = 0; t < tags.length; t++) {
            var tagData = {
                "tag": tags[t].get("tag"),
            }
            console.log("Tag Data: " + tagData);
            tagsData.push(tagData);
        }
        projectsData[tags] = tagsData;
        console.log("Step 2. Tags Data: " + JSON.stringify(tagsData));

        var refereesQuery = project.relation('referees');
        return refereesQuery.query().find();
    }).then(function(referees) {
        var refereesData = [];
        for(var r = 0; r < referees.length; r++) {
            var refereeData = {
                "name": referees[r].get("name"),
                "role": referees[r].get("role"),
                "emailAddress": referees[r].get("emailAddress"),
                "phoneNumber": referees[r].get("phoneNumber"),
                "linkedInUrl": referees[r].get("linkedInUrl"),
            }
            console.log("Referee Data: " + refereeData);
            refereesData.push(refereeData);
        }
        projectsData[referees] = refereesData;
        console.log("Step 3. Referees Data: " + JSON.stringify(refereesData));

        console.log("Everthing should be part of Projects Data here: " + JSON.stringify(projectsData));

        response.success(projectsData);
    }, function(error) {
        response.error("Error: " + error);
    });
});

推荐答案

有几个问题:

  • projectsDataprojectData
  • 之间的混淆
  • projectsData实际上不是必需的.
  • projectData必须在创建后(或应该在)使用的三个位置范围内&分配.
  • 在某些情况下,使用.then()可以满足标准同步流的需要.清除不必要的.thens将大大有助于解决范围问题.
  • Confusion between projectsData and projectData
  • projectsData isn't actually necessary.
  • projectData needs to be in scope in the three places it is (or should be) used after it is created & assigned.
  • In several cases .then() is used where standard synchronous flow will suffice. Purging the unnecessary .thens will help greatly in sorting out the scope issues.

除了重新整理代码之外,我所做的只是以下几点:

Doing little more than shuffling the code around, I arrive at the following :

Parse.Cloud.define('getProject', function(request, response) {
    var Projects = Parse.Object.extend("projects"); // with credit to @kRiZ
    var query = new Parse.Query(Projects);
    query.equalTo('projectUrl', request.params.projectUrl);
    query.find().then(function(projectsResult) {
        var project = projectsResult[0];
        var projectData = {
            'id': project.get('id'),
            'title': project.get('title'),
            'previewImage': project.get('previewImage'),
            'longDescription': project.get('longDescription'),
            'shortDescription': project.get('shortDescription'),
            'visibleToPublic': project.get('visibleToPublic'),
            'dateStart': project.get('dateStart'),
            'dateEnd': project.get('dateEnd'),
            'updatedAt': project.get('updatedAt'),
            'projectStatus': project.get('projectStatus')
        };

        //Now make the tags query and the referees query in parallel.
        var tagsPromise = project.relation('tags').query().find();
        var refereesPromise = project.relation('referees').query().find();

        // Aggregate the two promises with Parse.Promise.when(), and handle the responses.
        return Parse.Promise.when(tagsPromise, refereesPromise).then(function(tags, referees) {
            //Process the tags response
            projectData.tags = tags.map(function(t) {
                return {
                    'tag': t.get('tag')
                };
            });
            //Process the referees response
            projectData.referees = referees.map(function(r) {
                return {
                    'name': r.get('name'),
                    'role': r.get('role'),
                    'emailAddress': r.get('emailAddress'),
                    'phoneNumber': r.get('phoneNumber'),
                    'linkedInUrl': r.get('linkedInUrl')
                };
            });
            // Yay!
            response.success(projectData);
        });
    }).fail(function(error) {
        response.error('Error: ' + error);
    });
});

除了整体重排之外,唯一的重大变化是:

Apart from the overall rearrangement, the only substantial changes are :

  • 使用Array#map()将一个数组映射到另一个数组.
  • 并行进行两个查询,并使用Parse.Promise.when()汇总两个诺言.
  • Using Array#map() to map an array to another array.
  • Making two queries in parallel and using Parse.Promise.when() to aggregate the two promises.

这篇关于解析云代码承诺存在的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆