Siamak Ferdos Siamak Ferdos - 8 months ago 26
Javascript Question

Best way to update html after promise result

I wonder to know the best way of binding result of a promise which is as an injection to html tag using angular 2(I use ionic 2)...
As you know the main problem with async coding is loosing reference to the current object. It seems I should pass current object as a prameter to Promise function generator.
I searched internet for better solution but nothing I found! So is there any better approch?


Ionic 2 itself use observation and subscribe to do async proccess. But the major problem is that for existing functions which are not observable it couldn't work!


My approch:

Injectable class:

export class PromiseComponent {
doPromise = function (obj: any) {
return new Promise(function (resolve2) {
setTimeout(function () {
resolve2({ num: 3113, obj: obj });
}, 5000);
});
}
}


Call on click:

promiseVal = 0
doMyPromise() {
this.myPromise.doPromise(this).then(this.secondFunc);//UPDATED HERE
}


//UPDATED HERE
secondFunc = function (res) {
this.promiseVal = res.num
}


Html:

<div>{{promiseVal}} </div>
<button (click)="doMyPromise()">Do Promise</button>

Answer Source

If you want to consume a promise inside your component:

promiseVal = 0
doMyPromise() {
  this.myPromise.doPromise().then((res) => {
    this.promiseVal = res.num
  });
}

And I don't know the reasoning behind your Service but it usually is like this (optional):

export class PromiseComponent {
    doPromise() { //This method will return a promise
        return new Promise(function (resolve2) {
            setTimeout(function () {
                resolve2({ num: 3113, obj: obj });
            }, 5000);
        });
    }
}

After OP edited the post:

You can change this:

doMyPromise() {
    this.myPromise.doPromise(this).then(this.secondFunc);//UPDATED HERE
}

to

doMyPromise() {
    this.myPromise.doPromise(this).then(this.secondFunc.bind(this));//UPDATED HERE
}