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

  • JavaScript
  • Thread starter shivajikobardan
  • Start date
In summary, you need to create an asynchronous function, pass in a callback as the first argument, specify the type of callback as "async", and then use the await keyword to wait for the promise to be resolved.
  • #1
shivajikobardan
674
54
TL;DR Summary
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
  • #3
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.
 
  • #4
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)
 
  • #5
@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.
 
  • #6
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 shivajikobardan

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

What is callback hell?

Callback hell refers to the nested structure of callbacks in asynchronous JavaScript code, which can become difficult to read and maintain. This occurs when multiple asynchronous operations are dependent on each other, leading to a chain of callbacks within callbacks, making the code look like a "hellish" pyramid.

How can promises help rewrite callback hell?

Promises are objects that represent the eventual completion of an asynchronous operation. They allow for a more structured and readable way of handling asynchronous code, by using functions such as .then() and .catch() to handle the success or failure of the operation, instead of nesting callbacks.

What is the difference between callbacks and async/await?

Callbacks are functions that are passed as arguments to other functions, and are called when an asynchronous operation is completed. Async/await is a syntax introduced in ES2017 that allows for a more concise and synchronous-looking way of writing asynchronous code. It uses the keywords async and await to handle asynchronous operations, making the code appear more linear and easier to read.

How do we rewrite callback hell using promises?

To rewrite callback hell using promises, we can use the .then() method to chain multiple asynchronous operations together. This allows for a more structured and readable code, as each operation can be handled separately and in a linear manner, instead of being nested within each other.

Can we use async/await to rewrite any asynchronous code?

Yes, async/await can be used to rewrite any asynchronous code that uses callbacks or promises. However, it is important to note that async/await is not supported in all browsers, so it is recommended to use a transpiler like Babel to convert the code to a compatible version before deploying it.

Similar threads

Replies
9
Views
1K
Replies
1
Views
1K
Back
Top