我需要帮助来理解React Native中的承诺。老实说,我基本了解了这个想法,但是有人可以帮我更深入地解释。
我看了Mozilla上的Node promises Java Promise,但是我认为这是问题所在。
如果您有帮助,请不要简单地给我我想理解的答案“为什么”
我有两种方法。 “工作人员页面”
以及来自其他任何页面“ OTHER PAGE”的呼叫
工作人员页面
$ rsync --out-format="%t" "/source" "/destination"
2019/01/19 23:12:57 | home/nacho/backup_test/source 1
2019/01/19 23:12:57 | home/nacho/backup_test/source 1/001
2019/01/19 23:12:57 | home/nacho/backup_test/source 1/002
2019/01/19 23:12:57 | home/nacho/backup_test/source 1/003
2019/01/19 23:12:57 | home/nacho/backup_test/source 1/100
2019/01/19 23:12:57 | home/nacho/backup_test/source 1/file 100
2019/01/19 23:12:57 | home/nacho/backup_test/source 1/folder
2019/01/19 23:12:57 | home/nacho/backup_test/source 1/folder/004
2019/01/19 23:12:57 | home/nacho/backup_test/source 2
2019/01/19 23:12:57 | home/nacho/backup_test/source 2/006
然后我从另一个页面拨打电话
var Server_Ip = 'http://0.0.0.0:0000/'
let fetching = false;
exports.POST = function (url, data) {
if (fetching) return Promise.reject({D: 5});
fetching = true;
fetch(Server_Ip + url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => Promise.all([response.json()]))
.then(([response]) => {
fetching = false;
return response;
})
.catch(err => {
console.log("error catch search:", err.message);
fetching = false;
// Choose one, depends what you need.
return {D: 0};
return Promise.reject(err);
})
}
所以我故意弄乱服务器的IP以模拟可能的问题,它并没有做很多,但是当我发送垃圾邮件时,它返回了
Wkr.POST(string, data_send).then(response => {
console.log('response');
console.log(response);
//9 - SIGN IN PASSWORD MATCHES
if (response.D == 9) {
alert("YAY! GO THRU")
}
//8 - PASSWORDS DONT MATCH
else if (response.D == 8) {
alert("SORRY!, THE PASSWORDS DONT MATCH")
}
//7 - NO SUCH USER
else if (response.D == 7) {
alert("SORRY!, NO SUCH USER")
}
//6 - EMAIL IS NOT VALIDATED
else if (response.D == 6) {
alert("SORRY!, EMAIL IS NOT VALIDATED")
}
//5 - YOU HAVE TRIED TO LOGIN
else if (response.D == 5) {
alert("YOU HAVE TRIED TO LOGIN, PLEASE DONT SPAM")
}
//0 - ERROR
else if (response.D == 0) {
alert("ERROR");
} else {
alert("SHOULD NOT BEEN HERE");
console.log(response);
}
});
据我所知,该语句正在处理中,如果语句为“ 5”,则应点击
答案 0 :(得分:2)
原因是另一页中的then
回调不处理拒绝,即您用Promise.reject
生成的拒绝。要处理这种拒绝,您应该在另一页中链接一个.catch
回调:
.then(response => { // This is called when the promise was fulfilled
......
}).catch(reason => { // This is called when the promise was rejected
if (reason.D == 5) {
alert("YOU HAVE TRIED TO LOGIN, PLEASE DONT SPAM")
}
.....
});
另一件事:在工作程序页面中,您的函数不返回承诺(拒绝情况除外)。您需要返回 fetch
返回的内容:
return fetch(Server_Ip + url, {
^^^^^^^
在工作页面中,您还有一些未完成的代码:
// Choose one, depends what you need.
return {D: 0};
return Promise.reject(err);
...您需要选择。不能同时拥有。您选择哪种选择将确定在上述哪种处理程序(then
或catch
处理程序)中结束。还要注意,return Promise.reject(err)
与throw err
并没有多大区别(在then/catch
回调或promise构造函数回调的上下文中)。