【问题标题】:TypeError: Cannot read property 'then' of undefined within setTimeout()TypeError:无法读取 setTimeout() 中未定义的属性“then”
【发布时间】:2021-09-09 13:08:27
【问题描述】:

为什么我在解决 setTimeout() 中的承诺时得到 "TypeError: Cannot read property 'then' of undefined"?就像我下面的例子一样,调用 updateOrder2() 将 Promise 包装在 setTimeout() 中会返回错误。

HTML:

<input type="text" @change="validateInput(product)"/>

在 Vue.js 中

validateInput(product) {
   this.updateOrder1(product).then(response => {
     console.log(response); // done!
   });

   this.updateOrder2(product).then(response => {
     console.log(response); // error
   });
},

updateOrder2(product) {
   setTimeout(function() {
    return new Promise(function(resolve, reject) {
     resolve('done!');
    }, 500);
   });

updateOrder1(product) {
   return new Promise(function(resolve, reject) {
     resolve('done!');
   }, 500);
});

【问题讨论】:

  • updateOrder1(product) { 不应该有 500,我想这是一个错字
  • 在promise中移动setTimeout并在setTimeout中解决它返回promise in updateOrder2。当您返回 setTimeout 时,它会返回 setTimeout 函数的 id,它是一个数字,并且其中没有 then 函数

标签: javascript vue.js promise


【解决方案1】:

考虑这段代码:

function asyncCall() {
  return new Promise(function(resolve, reject) {
     resolve('done!');
  }
}

function call(){
  setTimeout(asyncCall, 500)
}

调用call() 不会执行异步调用。它只安排asyncCall 的执行并在asyncCall 执行之前返回。

setTimeout()本身不返回调度代码的结果,只返回timeoutID。

如果您希望在延迟函数执行后执行某些代码,最好的办法是向其传递回调。

function asyncCall(callback) {
   // execute some delayed code
   callback()
   // Or calling an async function
   asyncFunction().then(() => {
      callback()
   })
}

function call(callback){
  setTimeout(asyncCall, 500, callback)
}

call(function(){
  // This code will be executed after delayed code
})

【讨论】:

    【解决方案2】:

    你没有从 updateOrder2 函数返回任何东西,因此当你调用它时你会得到一个 undefined 。要解决此问题,您需要直接返回承诺并将 setTimeout 放入承诺正文中,如下所示:

    updateOrder2(product) {
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          resolve('done!');
        }, 500);
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-19
      • 2014-09-07
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 2014-11-29
      • 2016-09-20
      • 1970-01-01
      相关资源
      最近更新 更多