如何使用promises异步调用此函数

时间:2015-09-22 13:51:07

标签: javascript asynchronous parse-platform promise q

我正在尝试创建一个parse.com函数,该函数检查数据库中的记录并创建一个新记录或返回现有记录(如果存在)。我想异步这样做,我试图使用promises(我猜想)。语法让我有点困惑,这就是我尝试但是它正在把错误“不能调用方法”然后'未定义'我将如何将其写为正确的承诺。

  function createPersonIfDoesNotExist(personName)
  {
    var Person = Parse.Object.extend("Person");
    var personQuery = new Parse.Query(Person);
    personQuery.equalTo("Name", personName);
    personQuery.find({
      success: function(results) {
        console.log("Successfully retrieved " + results.length + " person.");
        if(results.length >0){
          console.log("Looks like this person exists already, no point it making a new one");
          var artist =  results[0];
          return artist;
        }
        else
        {
          // Create a new Person
          var person = new Person();
          return person;
        }
      },
      error: function(error) {
        console.log("Error: " + error.code + " " + error.message);
        return error;
      }
    });
  }

  var promise = createPersonIfDoesNotExist(personname);
  promise.then(console.log, console.error);

1 个答案:

答案 0 :(得分:1)

OP代码不会返回任何内容。它应返回的是由解析find()或save()方法生成的promise。

如果你编写的小函数可以在解析承诺返回函数上创建小的,增值的承诺,那么阅读和维护会变得更容易......

// return a promise that is fulfilled with a new Person with the given name
function createPersonNamed(personName) {
    var Person = Parse.Object.extend("Person");
    var person = new Person();
    person.set("Name", personName);
    return person.save();
}

// return a promise that is fulfilled with the first existing person with a given name
function findPersonNamed(personName) {
    var Person = Parse.Object.extend("Person");
    var personQuery = new Parse.Query(Person);
    personQuery.equalTo("Name", personName);
    return personQuery.first();
}

// return a promise that is fulfilled with either an existing person with a given name,
// or a newly created one if the Person does not exist
function findOrCreatePersonNamed(personName) {
    return findPersonNamed(personName).then(function(person) {
        return (person)? person : createPersonNamed(personName);
    });
}