How to rewrite callback hell using promises as well as async/await?

  • Context: JavaScript 
  • Thread starter Thread starter shivajikobardan
  • Start date Start date
Click For Summary

Discussion Overview

The discussion revolves around rewriting a nested callback structure, often referred to as "callback hell," using promises and async/await in JavaScript. Participants explore different approaches to refactor the code and clarify the concepts involved.

Discussion Character

  • Exploratory
  • Technical explanation
  • Debate/contested

Main Points Raised

  • One participant shares a callback hell example and expresses confusion about rewriting it using promises and async/await.
  • Another participant suggests using a state machine as a potential solution.
  • A different participant questions the clarity of the original request and advises replacing the context of the tutorial with something more familiar.
  • One participant critiques the use of unstructured blog posts for learning and points out that the provided code does not correctly resolve promises, highlighting the importance of understanding the underlying concepts.
  • Another participant expresses frustration with the original blog article and requests constructive feedback rather than criticism.
  • One participant proposes that tutorials often complicate learning by using artificial delays and provides a real-world example of using async/await with API calls to illustrate the concept.

Areas of Agreement / Disagreement

Participants express differing views on the effectiveness of the original tutorial and the best approach to learning about promises and async/await. There is no consensus on a single solution or method, and the discussion remains unresolved.

Contextual Notes

Some participants note that the original code provided by the thread starter does not function as intended due to incorrect promise resolution. Additionally, there are varying levels of familiarity with the concepts discussed, which may affect the clarity of communication.

shivajikobardan
Messages
637
Reaction score
54
TL;DR
callback hell rewriting using promises as well as async/await
JavaScript:
function createOrder() {
  setTimeout(function() {
    console.log("order created");
      setTimeout(function() {
         console.log("order received");
            setTimeout(function() {
               console.log("preparing food");
                  setTimeout(function() {
                      console.log("order ready");
                          setTimeout(function() {
                             console.log("order delivered");
                          }, 6000)
                   }, 4000)
             }, 5000)
      }, 1000)
   }, 2000)
}

createOrder();
This is the callback hell in question.
https://learnwithtriveni.com/2022/08/19/callback-hell-in-javascript/

I want to rewrite it using promises and async awaits.

I've indeed done it with promises and async, as shown here:
JavaScript:
async function createOrder() {
  setTimeout(() => {
    console.log("order created");
  }, 1000)
}

createOrder().then(
  setTimeout(() => {
    console.log("order received");
  }, 2000))

  .then(
    setTimeout(() => {
      console.log("preparing food");

    }, 3000)
  )

  .then(

    setTimeout(() => {
      console.log("order ready");
    }, 4000)
  )

  .then(
    setTimeout(() => {
      console.log("order delivered");

    }, 5000)
  )
Now, I want to do the same using async and await and only using promises.
I know the full syntax of async/await and promises as well.
I'll share if required.

Can you share the code for it? I'm really confused. It'd be really helpful to see and feel the code.

https://www.freecodecamp.org/news/h...llbacks-and-avoid-callback-hell-1bc8dc4a2012/

I've read this article but since I don't know much about burgers(or maybe this article wasn't a great fit for me anyways), this article was so difficult to read for me and I ended up learning nothing.
 
Technology news on Phys.org
Its a bit unclear for me what you are asking. If you really are failing to grasp the patterns presented in that tutorial because you don't know about burgers, then I suggest you mentally replace burgers with some other dish you do know about, or any other sequence of incremental work. Or, if you get lost at a specific step in the tutorial perhaps you can point to where?

And as always on Physics Forum, the more specific questions you ask the more likely you are to receive relevant answers.
 
shivajikobardan said:
Why do you insist on trying to learn from random, unstructured blog posts?

shivajikobardan said:
I've indeed done it with promises and async, as shown here:
That code does not work - that is not how you resolve a promise. It only appears to work because you set longer and longer timeouts - change the 1000 us in the first timeout to 9000 and you will be eating your snack before you order it!

shivajikobardan said:
I know the full syntax of async/await and promises as well.
Knowing the syntax of something is not the same as understanding how to do something (see above).

shivajikobardan said:
I've read this article but since I don't know much about burgers
Are you trying to make a joke? All you need to know about a burger is that it is a piece of cooked meat (beef) between two pieces of bread (buns) and this is explained in the article.
JavaScript:
//   1. Get beef
//   2. Cook the beef
//   3. Get buns for the burger
//   4. Put the cooked beef between the buns
//   5. Serve the burger (from the callback)
 
@pbuk simply i don't get that blog article at all. but I get random blogs because I learn from them, I read them. It'd be great if you could provide ways to fix the issue rather than only shouting at me.
 
I think that many tutorials confuse the issue by creating artificial delayed callbacks with setTimeout. It is easier to learn with a real example, for instance:
JavaScript:
// To use await inside a function it must be declared as async.
async function run() {
  try {
    // ipify.org will tell you your IP address.
    let response = await fetch('https://api.ipify.org?format=json');
    // We have to wait for a response before we can extract the IP address.
    const { ip } = await response.json();

    // Now use the ipinfo.io API to look up information about your IP address.
    response = await fetch(`https://ipinfo.io/${ip}/geo`);
    // Again you have to wait for it before you can do anything with it.
    const info = await response.json();
    console.log(info);
    // Let's return the IP address info so a caller can use it.
    return info;
  } catch (err) {
    console.error(err);
  }
};
 
  • Like
Likes   Reactions: shivajikobardan

Similar threads

  • · Replies 9 ·
Replies
9
Views
2K