Web开发学习求助:JavaScript代码改写(无箭头函数+async/await)
Hey there! I get that wrapping your head around refactoring promise-based code can be tricky at first—let's walk through these two tasks together, nice and slow.
First, a quick note: your original code has a misplaced error handler (the (error) => { ... } part is in the wrong spot, since fetch doesn't accept an error callback as its second argument). We'll fix that in both refactors to make sure error handling works as expected.
Task A: Refactor to avoid arrow functions entirely
We'll swap every arrow function out for traditional function expressions. Here's the revised code:
fetch("https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699") .then(function(res) { return res.json(); }) .then(function(result) { let items = result.items; console.log(items); }) .catch(function(error) { console.log(error); });
Key changes:
- Replaced
res => res.json()withfunction(res) { return res.json(); }(traditional function expression with explicit return) - Swapped
(result) => { ... }forfunction(result) { ... } - Moved error handling into a proper
.catch()method (fixing the original code's structure issue) - Added
letto declareitemsexplicitly (avoids creating an accidental global variable)
Task B: Refactor to use async/await
Async/await lets us write promise-driven code that reads more like straightforward synchronous code. We'll wrap everything in an async function and use try/catch for error handling:
async function fetchBookData() { try { const res = await fetch("https://www.googleapis.com/books/v1/volumes?q=isbn:0747532699"); const result = await res.json(); const items = result.items; console.log(items); } catch (error) { console.log(error); } } // Make sure to call the function to run the code! fetchBookData();
Key changes:
- Created an
asyncfunctionfetchBookData()(any function usingawaitmust be markedasync) - Used
awaitto pause execution until each promise resolves (replacing the.then()chain) - Wrapped the logic in a
try/catchblock to handle errors (this takes the place of the.catch()method in the promise chain) - Used
constfor variables that don't change (a clean, safe coding practice) - Added a call to
fetchBookData()so the code actually executes
内容的提问来源于stack exchange,提问作者jeMcFadzean

