[英]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.