javascript es6 async await基础使用 解决异步赋值问题

toSearch(v) {
      let haha = this.loadData()
	  console.log(haha)
 },
loadData() {
      setTimeout(() => {
        if (true) {
           return('ok')
        } else {
            return('false')
        }
       }, 1000)
 },

↑  此时想要拿到haha的值是拿不到的,因为loadDate是异步,所以可以利用asyna 和await来解决↓


async toSearch(v) {
      let haha = await this.loadData()
	  console.log(haha)
},
loadData() {
      return new Promise(function(resolve, reject) {
  	        setTimeout(function() {
                if (true) {
                   resolve('ok')
                } else {
                    reject('false')
                }
			
  		    }, 1000)
  	    })
 },

猜你喜欢

转载自blog.csdn.net/lanbaiyans/article/details/130685650