我认为,一个简单的例子是如何使用MDN DOCS的承诺。
作为一个例子,他们使用API Fetch,然后是两种类型,一种是正常的,另一种是混合的,其中async和Promise混合在一起。
简单的例子
async function myFetch() {
let response = await fetch("coffee.jpg");
// Added manually a validation and throws an error
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
let myBlob = await response.blob();
let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement("img");
image.src = objectURL;
document.body.appendChild(image);
}
myFetch().catch((e) => {
// Catches the errors...
console.log("There has been a problem with your fetch operation: " + e.message);
});
混合方法
由于async关键字将一个函数转换为一个promise,你可以重构你的代码,使用promise和await的混合方法,将函数的后半部分引入一个新块,使其更加灵活:
async function myFetch() {
// Uses async
let response = await fetch("coffee.jpg");
// Added manually a validation and throws an error
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.blob();
}
myFetch()
.then((blob) => {
// uses plain promise
let objectURL = URL.createObjectURL(blob);
let image = document.createElement("img");
image.src = objectURL;
document.body.appendChild(image);
})
.catch((e) => console.log(e));
添加错误处理
正常的
async function myFetch() {
try {
let response = await fetch("coffee.jpg");
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
let myBlob = await response.blob();
let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement("img");
image.src = objectURL;
document.body.appendChild(image);
} catch (e) {
console.log(e);
}
}
myFetch();
混合(最好的)
async function myFetch() {
let response = await fetch("coffee.jpg");
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.blob();
}
myFetch()
.then((blob) => {
let objectURL = URL.createObjectURL(blob);
let image = document.createElement("img");
image.src = objectURL;
document.body.appendChild(image);
})
.catch(
(
e // Not need a try catch. This will catch it all already!
) => console.log(e)
);
最好的解决方案
给出的最佳解决方案遵循这些原则,但增加了更清晰的答案是:> StackOverflow: try/catch block with async/await
我相信。在这里
function promiseHandle(promise) {
return promise.then((data) => [null, data]).catch((err) => [err]);
}
async function asyncFunc(param1, param2) {
const [err, data] = await promiseHandle(expensiveFunction(param1, param2));
// This just to show, that in this way we can control what is going on..
if (err || !data) {
if (err) return Promise.reject(`Error but not data..`);
return Promise.reject(`Error but not data..`);
}
return Promise.resolve(data);
}