Parse 中无操作 Promise 的语法是什么?

What's the syntax for a no-op Promise in Parse?

我经常发现自己在编写 beforeSaveafterSave 时使用这种形式的承诺:

beforeSavePromise: function (request) {

    var recipe = request.object;

    var promises = [
        doFooIfNeeded(recipe),
        doBarIfNeeded(recipe),
        doQuuxIfNeeded(recipe)
    ];

    return Parse.Promise.when(promises)
},

其中每一个都是有条件的操作,只有当一个或多个特定字段变脏时才执行操作。因此,例如,doFooIfNeeded 可能类似于:

if (recipe.dirty('imageFile')) {
    return /* some Promise that updates thumbnails of this image */; 
} else {
    return Parse.Promise.as();  // The no-op Promise. Do nothing!
}

我的问题是,Parse.Promise.as() 真的是空操作 Promise 吗?还是 new Parse.Promise() 更正确?

Parse.Promise.as() 技术上会给你一个状态设置为 resolved 的 Promise。当你 return 这个 Promise 时,它​​的回调将被成功触发。您可以提供一个值作为参数,这基本上会触发该值的回调。根据 Promise creation 上的 Parse 指南,new Parse.Promise() 创建了一个 Promise,它的状态是 既没有 设置为 resolved 也没有 failed。这使您可以根据需要灵活地手动管理其状态。

由于所有 "dirty" 个结果都为聚合提供了一个已解决的承诺,您可以为每个 "clean" 个结果选择以下列任何方式进行贡献:

  1. 不要在数组中放入任何东西,
  2. 在数组中输入一个值,
  3. 在数组中放入一个已解决的承诺,
  4. 在数组中放入一个被拒绝的承诺。

(1)、(2) 和 (3) 将保证无论 clean/dirty 结局如何(除了一些不可预测的错误),聚合承诺都会解决。

(4) 将导致聚合承诺仅在所有结果都是 "dirty" 时才解决,或者一旦任何一个 "clean" 结果出现就拒绝。

实际上,选择是在 (2) 和 (4) 之间,具体取决于您希望聚合承诺的行为方式。 (1) 会使聚合过程复杂化,并且 (3) 会不必要地昂贵。

当一切都已经 "clean" 或已被清理时,聚合承诺似乎是合适的,因此我建议 (2),在这种情况下你的 foo()/bar()/quux()函数可以这样写:

function foo() {
    return recipe.dirty('imageFile') ? updates_thumbnails() : true; // doesn't have to be `true` or even truthy - could be almost anything except a rejected promise. 
}

并汇总问题中的结果:

$.when([ foo(recipe), bar(recipe), quux(recipe) ]).then(function() {
    //all thumbnails were successfully updated.
}).fail(function() {
    //an unexpected error occurred in foo(), bar() or quux().
});