you should mostly use async/await, but in some cases, it's OK to use promises.
The Catch 22 is: how does one become competent with promises if one predominantly uses async/await?
async/await accommodates a synchronous mindset leaving everybody in their comfort zone while promises require a shift in thinking - breaking processing into (micro)tasks ("Many of us are using promises without really understanding them", 2015; The Event Loop, 2018).
Exploiting opportunities for concurrent asynchronous execution is possible in async/await with Promise.all() and Promise.allSettled() but a synchronous mindset isn't exactly honed towards recognizing these type of opportunities.
Also before async/await I always found it clearer to use function declarations instead of inline anonymous function expressions.
importaxiosfrom'axios';constreportInfo=(info)=>console.log(infoToMessage(info));constlogError=(error)=>console.log(errorToMessage(error));fetchInfoByTitle('in quibusdam tempore odit est dolorem').then(reportInfo)// 'Post (id: 12) with title "in quibusdam tempore odit est dolorem" has 5 comments.'.catch(logError);functionfetchInfoByTitle(title){returnaxios.get('https://jsonplaceholder.typicode.com/posts').then(fetchComments);functionfetchComments(res){constpost=findPostByTitle(title,res.data);if(!post)return{title};// nothing to doreturnaxios.get(`https://jsonplaceholder.typicode.com/comments?postId=${post.id}`).then(assembleInfo);functionassembleInfo(res){constcomments=res.data;return{title,post,comments,};}}}functionfindPostByTitle(title,posts){constfindTitle=title.toLowerCase();returnposts.find((p)=>p.title.toLowerCase()===findTitle);}functioninfoToMessage(info){if(!info.post)return`No post with a title of "${info.title}" found.`;const{post,comments}=info;constresult=comments.length!==1?`${comments.length} comments`:`1 comment`;return`Post (id: ${post.id}) with title "${post.title}" has ${result}.`;}functionerrorToMessage(error){consturl=error?.config?.url;return`Error: ${error.message}`+(url?`; url: ${url}`:'');}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
The Catch 22 is: how does one become competent with promises if one predominantly uses
async/await
?async/await
accommodates a synchronous mindset leaving everybody in their comfort zone while promises require a shift in thinking - breaking processing into (micro)tasks ("Many of us are using promises without really understanding them", 2015; The Event Loop, 2018).Exploiting opportunities for concurrent asynchronous execution is possible in
async/await
with Promise.all() and Promise.allSettled() but a synchronous mindset isn't exactly honed towards recognizing these type of opportunities.Also before
async/await
I always found it clearer to use function declarations instead of inline anonymous function expressions.