最近在開發小程序的是否,一個文章頁面,要先從服務器獲取文章信息,再獲取評論。這個順序不能反了(先獲取到評論,在獲取到文章內容),也不能混亂了(獲取評論的地方獲取到了文章的返回信息,這個我沒有遇見過,可能是js有機制不會搞混),總之是需要在獲取到文章內容之后在獲取評論。
如果直接寫(偽代碼)
wx.request({獲取文章})
wx.request ({獲取評論})
就不行了,如果文章查詢比較慢,就是先顯示評論,后顯示文章了,可能有的同學做了占位字符這些東西,我不了解,沒做過。
那么我們需要一個先執行查詢文章,返回后,在執行查詢評論,代碼如下(使用到了es6的 promise),網上看了些promise的使用,但是都太啰嗦了,我只想簡單使用,折騰之后,總結如下:
//測試promise,只有resolve()后才會執行then中的語句 new Promise(function(resolve){ setTimeout(function(){ console.log('1') if(txt){ resolve() } },2000) }).then(function(){ console.log(2) })
上面的代碼,應該很清楚了,如果 txt 為真,那么就執行resolve(),這個是告訴promise執行成功(如果沒有執行resolve,就不會執行then())。那么我的需求就能實現了。
settimeout是為了模擬服務器返回的場景。
(function(){ new Promise(function(resolve,reject){ setTimeout(function(){ console.log(1) // resolve() reject() },3000) }) .then(function(){ console.log(3) }) .catch(function(){ console.log(4) }) })()
上面的代碼會先輸出1,在輸出4,如果把reject()注釋掉,取消resolve()的注釋,那么就是先輸出1,在輸出3.
可以多層嵌套實現:
(function(){ new Promise(function(resolve,reject){ setTimeout(function(){ console.log(1) resolve() // reject() },3000) }) .then(function(){ console.log(3) new Promise(function(resolve,reject){ setTimeout(function(){ console.log(5) reject() },200) }) .then(function(){ console.log(6) }) .catch(function(){ console.log(7) }) }) .catch(function(){ console.log(4) }) })()
