0

I have an application that currently uses Angular 1.7 and we have an IHTTPPromise (updateCase) where we then process the code on the then() method after it has resolved

Before the first then() I want to chain another then() to set a waiting period of x milliseconds

I cannot use setTimeout() just in that then as that does not return a Promise.

In Angular 1.7, how can I create a new Promise to contain the setTimeout and then resolve and allow me to have chained then statements?

this.caseService.updateCase(updateCaseRequest)
//***WANT TO ADD A WAIT HERE
    .then(
    response => {
        this.showUpdateComplete();
        this.getCases();
        this.$scope.selectedCase = selectedCase;
    })
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Mike
  • 2,391
  • 6
  • 33
  • 72

2 Answers2

1

Use the $timeout Service:

this.caseService.updateCase(updateCaseRequest)
.then( response => {
    return this.$timeout( (_ => response) , delay );
}).then( response => {
    this.showUpdateComplete();
    this.getCases();
    this.$scope.selectedCase = selectedCase;
})

The return value of calling $timeout is a promise, which will be resolved when the delay has passed and the timeout function, if provided, is executed.

For more information, see

georgeawg
  • 48,608
  • 13
  • 72
  • 95
0

If you need to delay requests or other things more often by using something within the then chain, you could use the following:

/** Can be used within a then-chain to delay the next then in the chain ;) */
export const delayPromise = (ms: number, value: any) => new Promise((resolve) => { setTimeout(() => resolve(value), ms); });
this.caseService.updateCase(updateCaseRequest)
    .then(res => delayPromise(res, 1000)) // Wait 1 second
    .then(response => {
            this.showUpdateComplete();
            this.getCases();
            this.$scope.selectedCase = selectedCase;
        }
    );

Edit: cannot be used in angularjs context - see comments

Eweren
  • 277
  • 1
  • 12
  • with the delayPromise constm, I get the message "Promise only refers to a type but is being used as a value here" – Mike Mar 10 '20 at 11:59
  • are the argument inter-changed? `delayPromise(1000,res)`? – Eliseo Mar 10 '20 at 12:05
  • `Promise` and `setTimeout` should not be used/suggested. Angularjs has specific services for that (`$q` and `$timeout`) – Bill P Mar 10 '20 at 13:30
  • 1
    The ES6 Promises returned by `new Promise` are not integrated with the AngularJS framework and its execution context. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc. – georgeawg Mar 10 '20 at 15:07