最近在开发小程序的是否,一个文章页面,要先从服务器获取文章信息,再获取评论。这个顺序不能反了(先获取到评论,在获取到文章内容),也不能混乱了(获取评论的地方获取到了文章的返回信息,这个我没有遇见过,可能是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) }) })()