采用定时器返回 promise 会报错, Cannot read property 'then' of undefined

版权声明: https://blog.csdn.net/Gochan_Tao/article/details/87933835

比如在 setInterval 或者 setTimeout 里 return new Promise, 然后调用该方法,就会报错,小程序里面会报 Cannot read property ‘then’ of undefined

 test: function () {
    setTimeout(()=>{
      return new Promise((resolve, reject) => {
        resolve(666)
      })
    },3000)
 },
 onShow: function () {
	 this.test().then(res =>{
		console.log(res)
	 })
 }

上面这样使用 promise 会报错,应该将定时器放在 Promise 里面,以上代码修改为:

 test: function () {
    return new Promise((resolve, reject) => {
      setTimeout(()=>{
        resolve(666)
         },3000)
    })
  },
 onShow: function () {
	this.test().then(res =>{
		console.log(res) // 3秒后会打印出 666
	})
 }

猜你喜欢

转载自blog.csdn.net/Gochan_Tao/article/details/87933835