ES(二)async/await理解及用法

async是属于ES7里面内容,是定义一个异步函数,该函数会返回一个 promise 对象,可以通过 .then 的形式来调用。
eg:

 async  function resolveAfter2Seconds () {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve('resolved')
          }, 2000)
        })
      }
  resolveAfter2Seconds().then(index => {
    console.log('then', index)
  })

await就是等待 async 的异步执行,而且只能在 async 里面定义!
eg:

  let _this= this
  async function getStockPriceByName(name) {
    console.log('async', 1)
    var stockPrice = await _this.getStockPrice('symbol');
    console.log('async', 2)
    return stockPrice;
  }
  getStockPriceByName('goog').then(function (result){
    console.log(result);
  });

执行顺序是先打印 1,然后等待 getStockPrice 函数执行,然后打印 2 在返回出去 执行 .then 里面的方法。


定义一个请求

	  resolveAjax(parames){
			  return new Promise((resolve, reject) => {
				  this.$axios({
				  }).then(res => {
					  resolve(res)
				  }).catch(error => {
				  	reject(error)
				  });
			  })
		  },

这样引用

async next() {
 let result = await this.resolveAjax(parames)
 if(result){}
}

最后附上阮大神地址: http://www.ruanyifeng.com/blog/2015/05/async.html

你可能感兴趣的:(JavaScript)