今日已更新 222 条资讯 | 累计 40667 条内容
关于我们

标签:#await

找到 1 篇相关文章

AI 资讯

async/await without the pitfalls

async/await without the pitfalls Async/await is the bread and butter of modern JavaScript. It makes asynchronous code look synchronous, which is great for readability. But it comes with its own set of footguns that can bite you in production. Here's how to avoid them. Pitfall 1: Forgetting await in a loop You might write something like this, expecting each request to finish before the next starts: async function fetchAll ( urls ) { const results = []; for ( const url of urls ) { const res = await fetch ( url ); // this is fine, but see below results . push ( await res . json ()); } return results ; } That's actually correct. The issue arises when you forget await inside a .map() or .forEach() : // Wrong: map returns an array of promises, not data const data = urls . map ( async ( url ) => { const res = await fetch ( url ); return res . json (); }); // data is now an array of promises, not the JSON data async functions always return a promise. So if you use map with an async callback, you get an array of promises. To fix it, use Promise.all : const data = await Promise . all ( urls . map ( async ( url ) => { const res = await fetch ( url ); return res . json (); })); But beware: Promise.all fails fast. If one request fails, the whole thing rejects. If you need to handle failures individually, use Promise.allSettled instead. Pitfall 2: Swallowing errors silently A common mistake is to catch an error and do nothing, which makes debugging a nightmare: try { const data = await fetchData (); // process data } catch ( error ) { // do nothing? bad! } Always at least log the error. Even better, handle it gracefully or rethrow it: try { const data = await fetchData (); } catch ( error ) { console . error ( ' Failed to fetch data: ' , error ); throw error ; // rethrow if you want the caller to handle it } If you're using async/await , unhandled promise rejections can crash your app in Node.js. Always have a catch or a global handler. Pitfall 3: Sequential execution when you ne

2026-09-02 原文 →