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
SUMMARY

The discussion focuses on rewriting callback hell in JavaScript using Promises and async/await syntax. The original code demonstrates a series of nested setTimeout functions to simulate order processing, which leads to callback hell. A user attempted to refactor this using Promises but encountered issues with the implementation. The correct approach involves using async functions and properly resolving Promises to maintain the intended order of execution without nesting callbacks.

PREREQUISITES
  • JavaScript ES6 syntax, including Promises
  • Understanding of async/await functionality in JavaScript
  • Familiarity with setTimeout for asynchronous operations
  • Basic knowledge of API calls using fetch
NEXT STEPS
  • Learn how to properly implement async/await in JavaScript functions
  • Explore error handling in async functions using try/catch blocks
  • Study the differences between Promises and callbacks in JavaScript
  • Investigate real-world examples of using fetch API with async/await
USEFUL FOR

JavaScript developers, especially those looking to improve code readability and maintainability by avoiding callback hell. This discussion is beneficial for anyone transitioning from traditional callback patterns to modern asynchronous programming techniques.

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