用call调用的异步函数或apply从未解决

时间:2019-01-07 04:59:30

标签: javascript async-await

通过call调用或使用await进行应用的函数永远无法解析,请检查以下代码段

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();

2 个答案:

答案 0 :(得分:0)

仅扩展@CertainPermances注释-调用是一种函数方法,用于在函数内部为其分配选项,您不能在对象上使用它

(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();

})();

答案 1 :(得分:0)

我用错误的方式问了这个问题,我最终使用了如下正确的语法

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();