简体   繁体   English

Javascript造成混乱

[英]Javascript Promises confusion

I'm trying to figure out Promises with Parse. 我试图找出带有Parse的Promises。

What I want to do is get a lot of jobs, and then perform an update for each job. 我要做的是得到很多工作,然后为每个工作执行更新。

var queryJobs = new Parse.Query("Jobs");
queryJobs.find().then(function (results) {

    // Loop thorugh all jobs
    for (var i = 0; i < results.length; i++) {
        var job = results[i];

        // Here. I want to run an update on all object and then continue. 
    }

    return ????;

}).then(function () {
    status.success("Finish");
}, function () {
    status.error("Error");
});

I tried this without luck. 我没有运气尝试过。 The push block is never executed. 推块永远不会执行。

var queryJobs = new Parse.Query("Jobs");
queryJobs.find().then(function (results) {

    var promises = [];

    // Loop thorugh all jobs
    for (var i = 0; i < results.length; i++) {
        var job = results[i];


        promises.push((function () {

             // This is never executed. 

            var promise = new Parse.Promise();

            var query = new Parse.Query("Jobs");
            query.first({
                success: function (object) {
                    // ... Do something here.... 
                    promise.resolve();
                },
                error: function () {
                    promise.resolve();
                }
            });

            promise.resolve();
            return promise;
        }));
    }

    return Parse.Promise.when(promises);

}).then(function () {
    status.success("Finish");
}, function () {
    status.error("Error");
});

Thanks in advance 提前致谢

UPDATE UPDATE

I've changed the code, and I get into the callback, however, the query is not executed. 我已经更改了代码,然后进入了回调,但是查询未执行。

        ...

        promises.push((function () {

            // GET HERE
            var promise = new Parse.Promise();

            var query = new Parse.Query("Jobs");
            query.first({
                success: function (object) {
                    console.log("CALLBACK");
                    promise.resolve();
                },
                error: function () {
                    console.log("CALLBACK");
                    promise.resolve();
                }
            });
        }()));

    return Parse.Promise.when(promises);

You have to add promises to promises , not functions . 您必须在承诺中添加promises ,而不是功能 You need to call the function so that it returns the promise: 您需要调用该函数,以便它返回 promise:

   promises.push((function () {
       // ...
   }()));
 // ^^

Furthermore you have to remove the promise.resolve(); 此外,您必须删除promise.resolve(); call before the return statement. return语句之前调用。 The promise should only be resolved after the query succeeded. 仅应查询成功才能解决承诺。 As it currently is, the promise is resolved immediately. 就目前而言,承诺会立即得到解决。

Here is how I would set this up: 这是我要设置的方式:

var failure = new Parse.Promise();
var success = new Parse.Promise();

var queryJobs = new Parse.Query("Jobs");
queryJobs.each
(
    function( job )
    {
        //Do your changes to the job
        return job.save().then
        (
            function( job )
            {
                return Parse.Promise.as( "job saved" );
            },
            function( error )
            {
                failure.reject("There was an error trying to save a job: " + error.message);
                return failure;
            }
        );
    }
).then
(
    function( results )
    {
        success.resolve("Successfully updated all the jobs" )
        return success;
    },
    function( error )
    {
        failure.reject("There was an error trying to query for Jobs: " + error.message);
        return failure;
    }
).then
(
    function( success )
    {
        response.success( success );
    },
    function( failure )
    {
        response.error( failiure );
    }
);

This may not work out of the box, but it has a few key features that may help you. 这可能不是开箱即用的,但是它有一些关键功能可能会对您有所帮助。

1) I know that one of the perks that is mentioned in the blog post and what not announces promises is that you can get rid of pyramid code, but if you want descriptive error messages, the pyramid code is a necessary evil. 1)我知道博客文章中提到的特权之一,并且没有宣布承诺,就是您可以摆脱金字塔代码,但是如果您想要描述性的错误消息,金字塔代码是必不可少的。 My first promise (queryJobs.each in this case) always has two .then()'s. 我的第一个承诺(在这种情况下为queryJobs.each)始终有两个.then()。 The second one always just does response.error( failure ) and response.success( success ). 第二个总是只做response.error(failure)和response.success(success)。

2) I create two promises, although you can use just one. 2)我创建了两个承诺,尽管您只能使用一个。 I prefer two so it is clear where I'm failing / succeeding. 我更喜欢两个,所以很清楚我在哪里失败/成功。 I return these where I reach a dead end/ the finish line. 我将这些退回到达死胡同/终点的地方。

3) I used query.each instead of query.find . 3)我使用query.each而不是query.find query.find() is limited to 1000 results, which, while it will probably be more than enough for a long time, will eventually cause you to hit your limit, and you'd need to start paginating your results. query.find()限于1000个结果,虽然很长一段时间可能会绰绰有余,但最终会导致您达到极限,因此您需要开始对结果进行分页。 Using query.each will perform your function on every single object that could be returned by the query. 使用query.each将对查询可能返回的每个对象执行功能。 One perk of query.each vs query.find and iterating through the results is that query.each performs it's callback on each object asynchronously, rather than a linear iteration. query.eachquery.find一个query.find ,遍历结果是query.each异步地对每个对象执行回调,而不是线性迭代。

4) In this case it would probably be better just to have return job.save() inside of the each block, but I wanted to show how I do the nested promise returns. 4)在这种情况下,最好在每个块中都包含return job.save(),但我想展示如何做嵌套的promise返回。 This is what allows me to have very specific success / error statements. 这就是让我拥有非常具体的成功/错误陈述的原因。 This is important because even if one link in your promise chain fails, you will keep executing the next links. 这很重要,因为即使您的诺言链中的一个链接失败,您也将继续执行下一个链接。 The exception to this is if a promise is rejected and you don't have an error function until your last chain. 唯一的例外是,如果诺言被拒绝并且您直到最后一个链都没有错误函数。 The error will get passed from link to link until it finds an error function, which is fine, except it limits how much you can customize your error messages. 错误会从一个链接传递到另一个链接,直到找到错误函数为止,这很好,只是它会限制您可以自定义错误消息的数量。

I'll also note that what you have is probably going to return the same object again and again for that query.first() method, rather than working with the specific job from the first query. 我还将注意到,您拥有的内容可能会为该query.first()方法一次又一次返回同一对象,而不是处理第一个查询中的特定作业。 Like, you are iterating through your jobs, but instead of doing anything with each job, you're getting the first job and doing something with it again and again. 就像,您正在遍历工作,但是您没有在每项工作上都做任何事情,而是在获得第一份工作,然后一次又一次地做某事。 I don't think that's what you actually wanted, but maybe this is meant to be a "learn promises" post rather than something functional. 我认为这不是您真正想要的,但这也许是一个“学习承诺”的帖子,而不是功能性的文章。

Anyway, hope I helped a bit. 无论如何,希望我能有所帮助。 Let me know if you have questions and I'll do my best to answer them. 如果您有任何问题,请告诉我,我会尽力解答。

edit: I know my style varies greatly from others'. 编辑:我知道我的风格与别人的相差很大。 I like opening and closing brackets on a new line, for the most part. 在大多数情况下,我喜欢在新行上打开和关闭括号。 I actually read in javascript that this can sometimes cause errors. 我实际上读过javascript,这有时可能会导致错误。 I forget the specific cases, but this is not one of them. 我忘记了具体情况,但这不是其中之一。 But feel free to edit the style back to how you prefer it. 但是,请随时将样式修改回您喜欢的样式。

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

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