微信小程序使用 async await

微信小程序使用 async await

撰寫本文的目的是因爲我在Internet上找不到我想要的文章。谷歌已經很久了,百度已經很久了。其中大多數是以前的文章,可能難以理解,或者一步太繁瑣。

第一步:添加增強編譯

沒錯,只需一步就可以開始使用並體驗 async 帶來的便利。

在這裏插入圖片描述

第二步:開始使用並體驗

首先考慮一下爲什麼我們使用 async。我們中的一些人發送了一個請求,但是我們需要獲取請求返回的值並使用它。但是小程序請求經常是這樣的。

	var res = null
	wx.request({
      url: 'XXXXXX',
      success: function (e) {
        res = "一點寒芒先到," 
      },
    })
    console.log(res)
    console.log("隨後搶出如龍。")

我們想要輸出 一點寒芒先到,隨後槍出如龍。
但往往輸出的是 null 隨後槍出如龍。

當然,有時我們可以使用 Promise 來滿足我們的需求,然後使用then()。

	var app = getApp();
	app.post("XXXXX")
	.then(res=>{
		console.log("一點寒芒先到")
		console.log("隨後搶出如龍。")
	})
    

但是您必須記住,我們不會按順序輸出該語句,而是獲取請求後返回的值並使用它執行我們想要做的事情。

Promise 很好,但是請求的數量非常大,下一個請求需要上一個請求的返回值,我們應該怎麼做。

post: function (url, data) {
    var promise = new Promise((resolve, reject) => {
      var that = this
      var postData = data
      wx.request({
        url: url,
        data: data,
        method: 'GET',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        success: function (res) {
          //服務器返回數據
          resolve(res)//根據數據格式需求返回
        }
      })
    })
    return promise
  },
	var app = getApp();
	app.post("XXXXX")
	.then(res=>{
		res = "命運已做出了它的選擇!"
		
		app.post("XXXXX")
		.then(e=>{
			console.log(res)
			e = "勇士之魂,從未破滅。"
			
			app.post("XXXXX")
			.then(eee=>{
				console.log(e)
				console.log("德瑪西亞人從不退縮!")
				......
			})
		})
		
	})
    

您會發現要放置許多層。如果有更多數據,中間有更多判斷或請求太多,則很容易引起混亂。

如果我們使用 async 怎麼辦?

post: function (url, data) {
    var promise = new Promise((resolve, reject) => {
      var that = this
      var postData = data
      wx.request({
        url: url,
        data: data,
        method: 'GET',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        success: function (res) {
          //服務器返回數據
          resolve(res)//根據數據格式需求返回
        }
      })
    })
    return promise
  },
	
  onReady: async function () {
    var a = await app.post("xxx",msg)
    var b = await app.post("xxx",a)
    console.log(b) 
  },
	    

你發現了什麼?沒錯,Promise仍然被使用,它不會讓父親失望***,但是async 仍然具有優勢。

①:無需嵌套使用,正如上面代碼
②:錯誤處理;async 可以使用 try/catch 進行簡單的錯誤捕獲

test: async function() {
    try {
      await app.post()
    } catch(error) {
      console.log("出錯:未定義b")
    }
  },

而 Promise 則需要如下

test:  function() {
    try {
      app.post()
      .then(res=>{
      	//XXXXX
      	console.log(res)	
	  })
	  .catch(res=>{
	  	//XXXXX
	  	console.log(res)
	  })
    } catch(error) {
      console.log("出錯")
    }
  },

②:條件語句;使用 async

 test: async function() {
    if(await app.post()) {
      //XXXXX
    } else{
      //XXXXX
    }
  },

使用 Promise

 test: function() {
    app.post()
    .then(res=>{
		if(res){
			//XXXXXX
		}else{
			//XXXXX
		}
	})
	.catch(res=>{
		//XXXXX
	})
    
  },

此外,最重要的一點是,應將 await 與 async 結合使用。只能將 await 放入內部使用的 async 裝飾方法中。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章