首先,要阅读箭头函数,你必须了解箭头函数的返回值有两种方式:
const func = x => x * x; // concise body syntax, implied "return"
const func = (x, y) => { return x + y; }; // with block body, explicit "return" needed
现在,下面将介绍使用 Promise 链将代码转换为使用 async/await 的代码的步骤。通过完成任务B(将promise链替换为async/await),您将完成任务A(没有箭头函数的代码)
如果一个方法返回一个Promise,就像fetch和Body.json()一样,你可以等待它的结果:
const res = await fetch("https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699");
const result = await res.json();
items = result.items;
console.log(items);
要在不链接 .catch 的情况下处理错误,请使用 try/catch 块包装代码:
try {
const res = await fetch(
"https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699"
);
const result = await res.json();
items = result.items;
console.log(items);
} catch (error) {
console.log(error);
}
最后,await 关键字只能在异步函数docs 中使用,这就是为什么你必须将它包装到使用async 声明的函数中:
async function run() {
try {
const res = await fetch(
"https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699"
);
const result = await res.json();
items = result.items;
console.log(items);
} catch (error) {
console.log(error);
}
}
run();
您还应该知道,使用 async 关键字声明的任何函数也会返回一个您可以等待的 Promise。