gpt4 book ai didi

javascript - 如何使用 Promise 异步调用此函数

转载 作者:行者123 更新时间:2023-11-27 23:50:51 25 4
gpt4 key购买 nike

我正在尝试创建一个 parse.com 函数,该函数检查数据库中的记录并创建新记录或返回现有记录(如果存在)。我想异步执行此操作,并且我正在尝试使用 Promise(我想是 q )。语法让我有点困惑,这是我尝试过的,但它抛出错误“无法调用未定义的方法‘then’”我该如何将其写为正确的 promise 。

  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);

最佳答案

OP 代码不返回任何内容。它应该返回的是由 parse find() 或 save() 方法生成的 Promise。

如果您编写小函数,在解析 promise 返回函数上创建小的增值 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);
});
}

关于javascript - 如何使用 Promise 异步调用此函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32718732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com