[英]Proper mindset for use of promises?
我最近才看過Promise(JS不是我的強項),我不確定執行此操作的正確方法是什么。 承諾應該防止代碼向右漂移,但是當我遇到某種復雜的邏輯時,無論如何我最終都會嵌套得太深,所以我堅信我做錯了。
如果我將成功和失敗都作為json值返回,並且我也想處理格式錯誤的json,我會立即考慮執行以下操作:
fetch('json').then(function (result) {
return result.json();
}).catch(function (result) {
console.error("Json parse failed!");
console.error(result.text);
}).then(function (wat) {
// if (!result.ok) { throw...
}).catch(function (wat) {
// Catch http error codes and log the json.errormessage
});
當然,這是行不通的。 這是典型的同步代碼。 但這是我想到的第一件事。 我可以看到的問題:
我最好的嘗試是嵌套到我可能仍在使用回調的地步,但最終還是行不通,因為我仍然沒有解決以上任何問題:
fetch('json').then(function (response) {
if (!response.ok) {
throw response;
}
}).then(
function (response) {
response.json().then(function (data) {
console.log(data);
});
},
function (response) {
response.json().then(function (data) {
console.error(data.errormessage);
});
}
).catch(function () {
console.error("Json parse failed!");
// Where's my response????
});
執行此操作的“正確”方法是什么? (或至少少錯了)
如果您仍要調用response.json()
(用於成功和失敗的響應),並且希望一起使用response
,則將響應數據。 使用Promise.all
:
fetch('json')
.then(response => Promise.all([response, response.json()]))
.then(([response, data]) => {
if (!response.ok) {
console.error(data.errormessage);
} else {
console.log(data);
}
})
.catch(err => {
if (/* if http error */) {
console.error('Http error');
} else if (/* if json parse error */)
console.error('Json parse failed');
} else {
console.error('Unknown error: ' + err);
}
});
與不使用Promises時相比,您不應在Promises中將異常用於控制流。 這就是為什么fetch本身不僅僅拒絕對200以外的狀態碼的承諾。
這是一個建議,但是答案必然取決於您的特定需求。
fetch('json').then(function (response) {
if (!response.ok) {
response.json().then(function (data) {
console.error(data.errorMessage);
});
return ...;
}
return response.json().catch(function () {
console.error("Json parse failed!");
return ...;
});
}).catch(function (e) {
console.error(e);
return ...;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.