0

I'm new to Promises and would like to understand what is the correct way to avoid the 'callback hell' with promises, since I'm having the same exact problem as using callbacks

foo(a: number): Promise<boolean>{
    return doSomething(a).then((b)=>{
        return doAnotherThing(b).then((c)=>{
            return true;
        })
    })
}

Just look at this pyramid..

How can you avoid this?

Thanks in advance

Kesem David
  • 2,135
  • 3
  • 27
  • 46

3 Answers3

1

Just chain the promises instead of nesting them:

foo(a: number): Promise<boolean> {
    return doSomething(a).then((b) => {
        return doAnotherThing(b);
    }).then((c) => {
        return true;
    });
}

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

str
  • 42,689
  • 17
  • 109
  • 127
1

You can make a promise return a promise (or any other value), then chain that with .then():

foo(a: number): Promise<boolean>{
  return doSomething(a).then((b)=>{
      return doAnotherThing(b);
    }).then((c)=>{
      return true;
    });
}
Diego Cardoso
  • 973
  • 4
  • 14
0

If you use babel, ES2015 you could use await.

eg.

async function foo(a) {
  var b = await doSomething(a);
  var c = await doAnotherThing(b);
  return true;
}

presets: ES2015, stage-3

Keith
  • 22,005
  • 2
  • 27
  • 44
  • 2
    That's not ES2015. – Bergi Sep 30 '16 at 13:26
  • @Bergi Are you being pedantic?. – Keith Sep 30 '16 at 13:27
  • Yes, I am :-) If you don't want to care about version details, just call it "ES next" or "ES harmony". But async/await is not part of ES6 (ES2015), so please fix your answer and best link the relevant babel transformer that needs to be used – Bergi Sep 30 '16 at 13:30
  • btw. my reference was to babel, look on there website it says -> Babel learn ES2015, that was my reference. So in some ways your pedantic & then elitist response is what sometimes gives stack exchange a bad name. – Keith Sep 30 '16 at 13:37
  • I don't see async/await on the http://babeljs.io/docs/learn-es2015/ website anywhere – Bergi Sep 30 '16 at 13:39
  • Maybe, but I'm really not sure why sarcastic responses here get up votes. One of the reason's it's taken me so long to join Stack Exchange, there is a massive Ego problem. Maybe it was wrong of me to join & try and help. – Keith Sep 30 '16 at 13:42
  • But yet, copy and paste my code into Try It Out, and it seems to work. – Keith Sep 30 '16 at 13:45
  • Sorry, I don't want to come off as elitist or narcissistic - I just don't want wrong information in answers on topics I care about, so I point out mistakes in the hope that it helps everyone. So thanks for the edit and have a good day! – Bergi Sep 30 '16 at 13:46