The Network, Files, and Frequent Promises
I believe that the most common issues you'll run into that will make you want to switch your current function to async
mode usually have to do with: network requests, operating on files, and the frequent use and/or nesting of promises.
Network Requests
When I write network requests I always use the async/await
await combo. For me, it makes my code much more linear and readable. I also don't have to worry about returning the promise from fetch
(or axios
) when I'm done.
async function getPins(user, filterValue) {
const pins = await axios.get(...);
if (filterValue) {
return pins.filter(pin => pin.title.includes(filterValue));
}
return pins;
}
Files
async function handleFile(data, isEncrypted, isGzipped) {
if (isEncrypted) {
data = await decrypt(data, secret);
}
if (isGzipped) {
data = await ungzip(data);
}
return data;
}
Frequent Promises
async function init() {
const activeBoard = await getActiveBoard();
const boardMembers = await getBoardMembersFrom(activeBoard);
const allTasks = [];
for await (const tasks of boardMembers.map(getTasks)) {
allTasks.push(task);
this.setState({ tasks: [...allTasks] });
}
}
Note: you can use async/await
with Promises. There's no need to limit yourself to one or the other.
const test = async props => {
const data = await fetch('...').then(res => res.json());
console.log(data) /* do what you want with the data now */
}