1

I'm new to Angular so it's still rather difficult for me to write code in an efficient way. I've recently come upon this problem regarding Promise chaining and I'm wondering if there is a better way to go at it.

The gist is like this: I have function A, which needs result from function B. If I get a certain result from B, Then I would call C. B and C both returns Promises.

So in the end I got a very ugly block of code like this.

funcA(): Promise<MyObj> {
   return new Promise(function(resolve, reject) {
      funcB().then (res => {
          check if res satisfies condition    
          funcC().then( obj => { 
              process obj
              resolve(obj)
          }, reason => doSomething then reject)
      }, reason => doSomething then reject)
   }
}

The code works and serves my need, but it's difficult to read and I think there might be much better way to do this. The problem gets worse since there are a lot of places that I need to make similar call and sometimes the chaining might be even more complicated. So if anyone can provide a suggestion of how to better reformat my code or to how to rewrite function with Promise chaining I would greatly appreciate it.

Sylph
  • 151
  • 1
  • 11
  • See duplicate reference. In short: you should *not* need `new Promise` when `funcB()` already returns one. Just return it or whatever you chain to it with `then`. – trincot Nov 19 '18 at 11:21
  • Thanks. This is exactly what I've been looking for. – Sylph Nov 19 '18 at 13:19

2 Answers2

1

Since you're dealing with promises here, you can use the async await syntax for a cleaner implementation. Something along the lines of this:

async funcA() {
  try {
    const res = await funcB();
    if (check your condition with res) {
      const obj = await funcC();
      const resolvedObj = resolve(obj); // your custom implementation here;
      return resoalvedObj;
    }
  } catch (error) {
    console.log(`Something went wrong. Here's the error: ${JSON.stringify(error)}`);
  }
}

NOTE: This might not be the exact implementation that you should go for. But this definitely is a good starting point for you to clean your implementation.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
0

You could use Observables (here is an old answer of mine as to why you should), but since you asked for promises, let me deliver an answer.

The best way to deal with this is to simply chain them altogether. As long as your then returns something, you can make it easy, as shown here.

This would give :

funcA(): Promise<MyObj> {
   return promiseB()
     .then(res => promiseC(res))
     ...
     .then(res => promiseZ(res))
   );
}