【问题标题】:Can not use this inside a setInterval that is inside a promise [duplicate]不能在承诺内的 setInterval 内使用它[重复]
【发布时间】:2018-05-22 16:35:15
【问题描述】:

我正在使用 vuejs 开发一个应用程序。我想在 Promise 中使用 this,我希望能够在 .then 范围内调用函数或数据,为此我使用 this。但是,如果我在 .then 中执行此操作,则会出现错误,即使我将范围与箭头函数绑定,它似乎也会丢失。我能做什么?

javascript
  methods: {
    ...mapActions(['setCredentials']),
    doLogin() {
      console.log('credentials ' + this.username, this.password);
      this.$store.dispatch('connect', {
        username: this.username,
        password: this.password,
      });

      this.checkResult().then((interval) =>  {
        vm.$f7router.navigate('/favorites');

      })

},
    checkResult() {
    return new Promise(function(resolve) {

        var id = setInterval( () => {
                let condition = this.$store.state.isConnected
                   if (condition) {
                    clearInterval(id);
                    resolve(id);
                }

            setTimeout(() => {
                clearInterval(id);
                reject(id);
            }, 20000);
        }, 10);
    });
}

【问题讨论】:

    标签: javascript vue.js promise


    【解决方案1】:

    在实例化你的承诺时使用箭头函数:

    return new Promise((resolve) => { /* ... */ });
    

    【讨论】:

      【解决方案2】:

      错误是由于上下文绑定造成的。您可以使用 Arrow 函数,因为它们有自己的 no this 属性(它们依赖于其父函数的 this 属性)。

      更改return new Promise(function(resolve) {..

      return new Promise((resolve) => {..

      【讨论】:

        【解决方案3】:

        尝试在 promise 之前创建一个 var,例如: var self = this; 然后在 promise 中使用 self 而不是 this

        【讨论】:

        • 谢谢,但这次我遇到了 setTimout 的问题。即使我使用箭头函数、使用 that.reject 或仅使用 this.reject,也会在 setTimout 中为拒绝提供未定义的错误
        • 我知道我需要在函数签名中用 resolve 定义拒绝,谢谢。
        猜你喜欢
        • 2020-05-17
        • 1970-01-01
        • 2015-04-26
        • 2017-01-07
        • 2016-04-21
        • 2016-09-22
        • 1970-01-01
        • 1970-01-01
        • 2020-12-28
        相关资源
        最近更新 更多