【问题标题】:Understanding JavaScript promises in Parse理解 Parse 中的 JavaScript 承诺
【发布时间】:2015-10-23 15:48:08
【问题描述】:

我正在 Parse 中开发一个应用程序,我正在尝试理解 Promise。除了这里非常简单的示例之外,我没有找到很多工作示例:https://parse.com/docs/js/guide

我正在查询 _User 表。然后我在 _.each 循环中遍历用户。我在每次迭代的循环内运行 2 个云函数。我在什么时候创建承诺?我是否为循环中的每个云功能成功创建一个?或者我是否将每个成功返回值推送到一个数组中,并将其作为循环之外的承诺值?我都试过了,但似乎都找不到正确的语法。

我将把它分解成伪代码,因为这可能比实际代码更容易:

var query = new Parse.Query(Parse.User); query.find().then(function(users){

  • 在 _.each 循环中遍历每个用户,并为每个用户运行一个返回数字的云函数。
  • 如果数字 > 0,那么我将他们的用户名推送到 array1。
  • 然后我在用户上运行第二个云函数(仍在 _.each 循环内),它返回一个数字。
  • 如果数字 > 0,那么我将他们的用户名推送到 array2。

}).then(function(promisesArray){

// 我希望“promisesArray”是上一节中创建的 2 个数组,或者是它们的串联。

// 最终,我需要一个用户名列表。具体来说,上一节中从云函数中获得正数值的用户

  • 连接 2 个数组(如果它们尚未连接)
  • 删除重复项
  • 向数组中的用户发送推送通知 });

问题: - 我在什么时候创建和返回承诺以及我应该使用什么语法? - .then(function(promisesArray){ 应该是 .when(function(promisesArray){ (when 而不是 then)?

【问题讨论】:

    标签: javascript parse-platform


    【解决方案1】:

    感谢两位的想法!这就是最终奏效的方法:

    var query = new Parse.Query(Parse.User);
    query.find().then(function(users){
      var allPromises = [];
      var promise1, promise2;
    
      _.each(users, function(user){
        if(user.get("myvalue") != "undefined" && user.get("myvalue") != ""){
          promise1 = Parse.Cloud.run("getBatch1", {param1: param1value, param2: param2value})
          .then(function(numResult){
            if(Number(numResult) > 0){
              return Parse.Promise.as(user.getUsername());
            }
          });
        }
        allPromises.push(promise1);
    
        if(user.get("anothervalue")==true){
          promise2 = Parse.Cloud.run("getBatch2", {param1: param1value, param2: param2value})
          .then(function(numResult2){
            if(Number(numResult2) > 0){
              return Parse.Promise.as(user.getUsername());
            }
          });
        }
        allPromises.push(promise2);
      });
    
      // Return when all promises have succeeded.
      return Parse.Promise.when(allPromises);
    
    }).then(function(){
      var allPushes = [];
      _.each(arguments, function(pushUser){
        // Only add the user to the push array if it's a valid user & not already there.
        if(pushUser != null && allPushes.indexOf(pushUser) === -1){
          allPushes.push(pushUser);
        }      
      });
    
      // Send pushes to users who got new leads.
      if(allPushes.length > 0){
        Parse.Push.send({
          channels: allPushes,
          data: {
            alert: "You have new leads."
          }
        }, {
          success: function () {
            response.success("Leads updated and push notifications sent.");
          },
          error: function (error) {
            console.log(error);
            console.error(error);
            response.error(error.message);
          }
        });
      }
      response.success(JSON.stringify(allPushes));
    
    }, // If the query was not successful, log the error
    function(error){
      console.log(error);
      console.error(error);
      response.error(error.message);
    });
    

    【讨论】:

      【解决方案2】:

      我不熟悉 Parse API,但我会这样做。当然,我无法测试我的代码,所以请告诉我它是否有效:

      var query = new Parse.Query(Parse.User);
      query.find()
          .then(function(users) {
              var promises = [];
              users.forEach(function(user) {
                  // the first API call return a promise so let's store it
                  var promise = cloudFn1(user)
                      .then(function(result) {
                          if (result > 0) {
                              // just a way to say 'ok, the promise is resolved, here's the user name'
                              return Parse.Promise.as(user.name);
                          } else {
                              // return another promise for that second API call
                              return cloudFn2(user).then(function(res) {
                                  if (result > 0) {
                                      return Parse.Promise.as(user.name);
                                  }
                              });
                          }
                      });
      
                  // store this promise for this user
                  promises.push(promise);
              });
      
              // return a promise that will be resolved when all promises for all users are resolved
              return Parse.Promise.when(promises);
          }).then(function(myUsers) {
              // remove duplicates is easy with _
              myUsers = _.uniq(myUsers);
              // do your push
              myUsers.forEach( function(user) {
      
              });
          });
      

      【讨论】:

        【解决方案3】:

        首先,您需要了解 Promise 是什么。根据我对您正在尝试做的事情的理解,它应该看起来像这样:

        //constructs the Parse Object
        var query = new Parse.Query(Parse.User);
        
        //find method returns a Promise
        var res   = query.find()
        
        //good names will be a Promise of an array of usernames
        //whose value is above 0
        var goodNames = res
            .then(function(data) {
        
                //assumes the find method returns an array of
                //objects, one of the properties is username
                //we will map over it to create an Array of promises
                //with the eventual results of calling the AJAX fn
                var numberPromises = data.map(function(obj) {
        
                    //wrap the call to the cloud function in a new
                    //promise
                    return new Promise(resolve, reject) {
                        someCloudFn(obj.username, function(err) {
                            if (err) {
                                reject(err);
                            } else {
                                resolve(num);
                            }
                        });
                    }
                };
        
                //Promise.all will take the array of promises of numbers
                //and return a promise of an array of results
                return [data, Promise.all(numberPromises)];
            })
            .then(function(arr) {
        
                //we only get here when all of the Promises from the
                //cloud function resolve
                var data    = arr[0];
                var numbers = arr[1];
                return data
                    .filter(function(obj, i) {
        
                        //filter out the objects whose username number
                        //is zero or less
                        return numbers[i] > 0;
                    })
                    .map(function(obj) {
        
                        //get the username out of the query result obj
                        return obj.username;
                    });
            })
            .catch(function(err) {
                console.log(JSON.stringify(err));
            });
        

        现在,当您需要使用编号不为零的用户名列表时,您可以调用goodNamesthen 方法并获得结果:

        goodNames.then(function(listOfNames) {
            //do something with the names
        });
        

        【讨论】:

          猜你喜欢
          • 2017-01-20
          • 1970-01-01
          • 2015-02-26
          • 1970-01-01
          • 2022-01-22
          • 1970-01-01
          • 2015-02-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多