【问题标题】:Async function called with call or apply never resolved使用 call 或 apply 调用的异步函数从未解决
【发布时间】:2019-01-07 13:58:33
【问题描述】:

使用 call 调用或使用 await 应用的函数永远无法解析,请检查以下代码 sn-p

const obj = {
   resolveAfter2Seconds: function() {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve('resolved');
      }, 2000);
    });
  }
}

async function asyncCall() {
  console.log('calling');
  var result = await obj.resolveAfter2Seconds();
  console.log(result);//resolved

 var result2 = await obj.call("resolveAfter2Seconds");
  console.log(result2);//never alled
}

asyncCall();

【问题讨论】:

  • obj 不是函数。 obj.call 毫无意义。 Uncaught (in promise) TypeError: obj.call is not a function
  • 通过 call(),一个对象可以使用属于另一个对象的方法。因为只有一个全局对象。无需致电/申请。
  • 我明白了,我已经在另一个答案中澄清了......谢谢

标签: javascript async-await


【解决方案1】:

只是扩展@CertainPermances 注释 - call 是一个函数方法,用于在函数内部为 this 分配一个选项,你不能在对象上使用它

(function() {
    const obj = {
        resolveAfter2Seconds : function() {
            return new Promise(resolve => {
                setTimeout(() => {
                resolve('resolved');
                }, 2000);
            });
        }
    }

    async function asyncCall() {
        console.log('calling');
        var result = await obj.resolveAfter2Seconds();
        console.log(result);//resolved

        // var result2 = await obj.call("resolveAfter2Seconds");    caused an eror
        var result2 = await obj.resolveAfter2Seconds();
        // or
        var result2 = await obj.resolveAfter2Seconds.call( obj /* perhaps */); // which makes no difference at all because this = obj anyway
        console.log(result2);
    }

    asyncCall();

})();

【讨论】:

    【解决方案2】:

    我以错误的方式提出问题,我最终使用了正确的语法,如下所示

    const obj = {
       resolveAfter2Seconds: function() {
        return new Promise(resolve => {
          setTimeout(() => {
            resolve('resolved');
          }, 2000);
        });
      }
    }
    
    async function asyncCall() {
      console.log('calling');
      var result = await obj.resolveAfter2Seconds();
      console.log(result);//resolved
    
     var result2 = await obj["resolveAfter2Seconds"].call();
      console.log(result2);//never alled
    }
    
    asyncCall();
    

    【讨论】:

      猜你喜欢
      • 2011-03-22
      • 1970-01-01
      • 2012-07-25
      • 2013-11-08
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      相关资源
      最近更新 更多