Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I heard that promises are supposed to be linear in code in opposed to callbacks ("callback hell").

Though I still have a scenario similar to callback hell and hoping promises can make their promise and have a linear syntax equivalent to this problem code.

Given promises p(), q(),w() consider this code:

p().then(() => {
    q().then(() => {
       w().then(() => {
           // do something
       })
    })
})

Can we make an equivalent code which is not indented for every nested promise?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
152 views
Welcome To Ask or Share your Answers For Others

1 Answer

You should not nest the .then() handlers but let each .then() create and return a new Promise. This is how it was designed to work, otherwise you are still in the callback hell, now the version with promises. No big difference.

The code should be like this:

p()
  .then(() => {
    return q();
  })
  .then(() => {
    return w();
  })
  .then(() => {
    // do something
  });

If all that the .then() handlers do is to call the next function you can write it in a simpler form (read about arrow functions):

p()
  .then(() => q())
  .then(() => w())
  .then(() => {
    // do something
  });

Even more, if q and w are called without arguments, the code could be as simple as:

p()
  .then(q)
  .then(w)
  .then(() => {
    // do something
  });

Or you can go the extra mile and instead of using .then() and .catch() you use await. The code becomes even more clear and easy to read:

try {
  await p();
  await q();
  await w();
  // do something
} catch (err) {
  // write here the code you would write in the handler you pass to `.catch()
  // in the approach that uses Promises
}

Remarks

If the code above, using await, is used in a function then that function must be an async function (just put async in front of its definition).

The code that uses await may or may not be used outside of a function (i.e. at module's top level) depending on the runtime you use to run it (browser, Node.js etc).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...