gpt4 book ai didi

javascript - parse.com promise - 我需要在每个 "error"中有一个 "then"函数吗?

转载 作者:行者123 更新时间:2023-11-30 08:03:18 27 4
gpt4 key购买 nike

parse.com 提供了一个云代码部分,这样我就可以编写 javascript 代码来修改我的 parse.com 数据库。

我有这样一个云代码函数,可以做很多事情——比如,检查用户是否存在,如果用户存在,将一些数据保存在不同的表中,然后更新用户表以引用这个新表——所以我会有一个 parse.Query 检查用户是否存在,然后有几个 then 语句在另一个表上运行更新并让用户表引用这个新行。

在这种情况下,我是要有几个错误函数(例如每个parse.Query一个),还是可以接受一个错误函数在最后 then promise?

最佳答案

是的。它是可以接受的。

Promise 就像异常,每个 .then 都有一个错误函数,就像每个语句都有一个 .catch block :

try{
first();
} catch(e) {
//handle
}
try{
second();
} catch(e) {
//handle
}
try{
third();
} catch(e) {
//handle
}

通常,捕获一个更自然、更清晰

try {
first();
second();
third();
} catch (e) {
// handle error in whole flow.
}

同样的 promise :

 first().then(second).then(third).catch(function(e){ /* handle error */});

或者,像 Parse.Promise 这样没有 catch 的实现:

 first().then(second).then(third).then(null,function(e){ /* handle error */ });

控制流将与您预期的完全一样 - 如果 first 失败,则它将由 first 错误处理程序处理,并且它将 在此过程中执行和实现回调,因此:

Parse.promise.as(true).then(function(){
throw new Error("Promises are throw safe and throws are rejections! funstuff");
}).then(function(){
alert("This will never show");
}).then(function(){
alert("This will never show either");
}).then(null,function(e){
alert("This is the error handler!" + e.message);
}).then(function(){
alert("Since the error was handled this will show");
});

在考虑 promise 的行为方式时,请始终考虑同步模拟。

关于javascript - parse.com promise - 我需要在每个 "error"中有一个 "then"函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22787411/

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