Promise returning in Angular [duplicate]











up vote
1
down vote

favorite













This question already has an answer here:




  • What is the explicit promise construction antipattern and how do I avoid it?

    2 answers




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.










share|improve this question















marked as duplicate by trincot, Bergi promise
Users with the  promise badge can single-handedly close promise questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 19 at 11:28


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.















  • 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 at 11:21










  • Thanks. This is exactly what I've been looking for.
    – Sylph
    Nov 19 at 13:19















up vote
1
down vote

favorite













This question already has an answer here:




  • What is the explicit promise construction antipattern and how do I avoid it?

    2 answers




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.










share|improve this question















marked as duplicate by trincot, Bergi promise
Users with the  promise badge can single-handedly close promise questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 19 at 11:28


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.















  • 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 at 11:21










  • Thanks. This is exactly what I've been looking for.
    – Sylph
    Nov 19 at 13:19













up vote
1
down vote

favorite









up vote
1
down vote

favorite












This question already has an answer here:




  • What is the explicit promise construction antipattern and how do I avoid it?

    2 answers




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.










share|improve this question
















This question already has an answer here:




  • What is the explicit promise construction antipattern and how do I avoid it?

    2 answers




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.





This question already has an answer here:




  • What is the explicit promise construction antipattern and how do I avoid it?

    2 answers








angular typescript promise angular-promise






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 19 at 11:22









trichetriche

24.1k41950




24.1k41950










asked Nov 19 at 11:12









Sylph

408




408




marked as duplicate by trincot, Bergi promise
Users with the  promise badge can single-handedly close promise questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 19 at 11:28


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






marked as duplicate by trincot, Bergi promise
Users with the  promise badge can single-handedly close promise questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 19 at 11:28


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • 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 at 11:21










  • Thanks. This is exactly what I've been looking for.
    – Sylph
    Nov 19 at 13:19


















  • 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 at 11:21










  • Thanks. This is exactly what I've been looking for.
    – Sylph
    Nov 19 at 13:19
















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 at 11:21




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 at 11:21












Thanks. This is exactly what I've been looking for.
– Sylph
Nov 19 at 13:19




Thanks. This is exactly what I've been looking for.
– Sylph
Nov 19 at 13:19












2 Answers
2






active

oldest

votes

















up vote
1
down vote













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.






share|improve this answer




























    up vote
    0
    down vote













    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))
    );
    }





    share|improve this answer




























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      1
      down vote













      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.






      share|improve this answer

























        up vote
        1
        down vote













        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.






        share|improve this answer























          up vote
          1
          down vote










          up vote
          1
          down vote









          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.






          share|improve this answer












          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.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 19 at 11:25









          SiddAjmera

          11.4k21137




          11.4k21137
























              up vote
              0
              down vote













              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))
              );
              }





              share|improve this answer

























                up vote
                0
                down vote













                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))
                );
                }





                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  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))
                  );
                  }





                  share|improve this answer












                  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))
                  );
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 19 at 11:22









                  trichetriche

                  24.1k41950




                  24.1k41950















                      Popular posts from this blog

                      Create new schema in PostgreSQL using DBeaver

                      Deepest pit of an array with Javascript: test on Codility

                      Costa Masnaga