0

I am migrating AngularJS to Angular

Trying to replace $q with Promise

I have

$q.when(btn.onClick()).finally(test => {
    // code
})

I have replaced it with the below code and not sure if that is the exact replacement.

Promise.resolve(btn.onClick()).then(test => {
    // code
})

From $q.when() I see we can use .resolve() for .when()

but what is the replacement for .finally()

Dot Net Dev
  • 574
  • 8
  • 20

3 Answers3

1

Start by binding a component template button click to your template logic

<button (click)="onClick()">Click</button>
onClick() {}

Then you can use Promise.all for several promises, or .then for a single promise.

Although, if I may suggest, while migrating, you should consider using Observables, as they're way more powerful than promises and natively integrated with Angular.

Here is one of my previous answers to get started rapidly with Observables.

  • Thanks for the answer, I don't want to bind template logic to the component logic, So can I use .resolve() instead of .when() ? – Dot Net Dev Dec 11 '18 at 16:03
  • Well that's kind of Angular purpose, to bind the template to the class ... And resolve won't change that. Resolve is used to validate a promise, and `Promise.resolve` is used to create an instantly resolved promise. I don't know what `when` does, but you probably can, yes –  Dec 12 '18 at 08:04
0

Since you mention you're migrating, using observables is preferred when possible to using promises. From the documentation:

You can often use observables instead of promises to deliver values asynchronously. Similarly, observables can take the place of event handlers. Finally, because observables deliver multiple values, you can use them where you might otherwise build and operate on arrays.

https://angular.io/guide/comparing-observables

That being said, finally is a part of the promise API and can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally

  • I have tried to use `Promise.resolve().finally(() => {})`, and it says that Promise, does not have finally() mehtod. – Dot Net Dev Dec 11 '18 at 15:16
-1

//realised that's not the question. my bad!

You could use

.then(function(){
})

as many times as you want, theres no true replacement for finally() in my knowledge

Tom Edwards
  • 124
  • 1
  • 13