javascript - promise 结果后更新 html 的最佳方法

标签 javascript angular promise ionic2

我想知道绑定(bind) promise 结果的最佳方法,即使用 Angular 2(我使用 ionic 2)注入(inject) html 标签... 如您所知,异步编码的主要问题是丢失对当前对象的引用。看来我应该将当前对象作为参数传递给 Promise 函数生成器。 我在互联网上搜索更好的解决方案,但没有找到!那么有没有更好的方法呢?

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!

我的方法:

可注入(inject)类:

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

点击调用:

  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>

最佳答案

如果您想在组件内使用 Promise:

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

我不知道您的服务背后的原因,但通常是这样的(可选):

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

OP编辑帖子后:

您可以更改此设置:

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

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

关于javascript - promise 结果后更新 html 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43387183/

相关文章:

javascript - 在 Angular 2 中的 Observable 中获取数据后的队列/回调函数

Javascript Promise 不会解决

c - OpenMP 支持异步操作吗?

javascript - 警告不支持新 CSS3 标准的旧浏览器的用户

javascript - 如何动态添加文本框而不丢失以前文本框的值?

javascript - 计算页面加载的所有资源

javascript - 淡入完成后淡出后异步/等待超时

javascript - 为什么在jQuery中经过for循环后数组顺序是随机的?

Angular @ViewChild() 错误 : Expected 2 arguments, 但得到 1

angular - 树 Material angular 2选中状态