[英]Is using async/await the only way to receive a resolved promise from Promise.reject()?
我下面有以下代碼。 我想做的是分別處理網絡錯誤情況和返回的HTTP服務器錯誤情況。
fetch("$imageUploadUrl", {
method: "POST",
mode: "same-origin",
cache: "no-store",
credentials: "same-origin",
redirect: "error",
referrer: "origin",
body: formData
}).catch(function(error) {
failure("There was an error while uploading the image");
}).then(function(response) {
if (response.ok){
return Promise.resolve(response.json());
} else {
return Promise.reject(response.text())
}
}).then(function(result) {
success(result.location);
}).catch(function(errorText) {
return failure (errorText);
})
但是,與Promise.resolve()
不同, Promise.reject()
response.text()
在返回前不等待從response.text()
解析承諾。 我設法通過添加async / await來收到已解決的諾言:
fetch("$imageUploadUrl", {
method: "POST",
mode: "same-origin",
cache: "no-store",
credentials: "same-origin",
redirect: "error",
referrer: "origin",
body: formData
}).catch(function(error) {
failure("There was an error while uploading the image");
}).then(async function(response) {
if (response.ok){
return Promise.resolve(response.json());
} else {
return Promise.reject(await response.text())
}
}).then(function(result) {
success(result.location);
}).catch(function(errorText) {
failure(errorText);
});
這是達到我目標的唯一方法嗎?
我也嘗試這樣做:
fetch("$imageUploadUrl", {
method: "POST",
mode: "same-origin",
cache: "no-store",
credentials: "same-origin",
redirect: "error",
referrer: "origin",
body: formData
}).catch(function(error) {
failure("There was an error while uploading the image");
}).then(function(response) {
if (response.ok){
return Promise.resolve(response.json());
} else {
return Promise.reject(response.text())
}
}).then(function(result) {
success(result.location);
}).catch(function(textPromise) {
return textPromise;
}).then(function(text) {
console.log(text);
})
但是,即使我在上面的代碼中調用Promise.resolve()
時,也總是調用console.log
的最后一個,因為它附加在fetch函數本身的promise上。 你知道為什么會這樣嗎?
您可以等待諾言,然后拒絕它:
return response.text().then(text => Promise.reject(text));
那這個版本呢:
const options = {
method: 'POST',
mode: 'same-origin',
cache: 'no-store',
credentials: 'same-origin',
referrer: 'origin',
body: formData
}
async function parseResponse (response) {
try {
success(await response.json())
} catch () {
failure(await response.text())
}
}
function parseError (err) {
failure(`Error uploading file: ${err}`)
}
fetch('$imageUploadUrl', options)
.then(parseResponse)
.catch(parseError)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.