最近在学习慕课网的“旧岛小样”微信小程序,才对promise有了初步的了解,之前都是直接套用,现在做一下简单的个人笔记。
对于promise的了解,可以直接参考MDN或者菜鸟教程,里面有对promise的描述和使用,这里就不重复了
- Promise 对象用于执行异步操作,可以解决简单的回调函数中多层嵌套导致的回调地狱问题,当然解决这个回调地狱问题要正确地去使用promise才行;promise精髓:采用对象的方式保存了异步调用的结果;
- 正确的promise用法:
Page({
onLoad: function(options) {
functionA().then(res => {
})
.then(res => {
console.log(res, 'api的调用结果');
})
.then(res => {
console.log(res);
})
}
})
3.错误的promise用法
Page({
onLoad: function(options) {
functionA().then(res => {
console.log(res);
functionB().then(res => {
console.log(res);
})
functionC().then(res => {
console.log(res);
})
})
}
})
4.Promise.all和Promise.race的区别
5.“旧岛小样”微信小程序中对Promise.all的使用,代码如下所示:
Page({
onLoad: function(options) {
//等待的提示
wx.showLoading()
// id就是从外面获取到的id,在book组件点击事件中定义传递id的变量叫bid,所以这里也取bid
const bid = options.bid;
const detail = bookModel.getDetail(bid);
const comments = bookModel.getComments(bid);
const likeStatus = bookModel.getLikeStatus(bid);
// 从promise中用then方法取数据,同时发送三个请求
// 合并多个promise的实例,只有在三个子promise的请求发送完毕以后才会执行
Promise.all([detail, comments, likeStatus])
.then(res => {
console.log(res, 'Promise.all')
this.setData({
book: res[0], //取到Promise.all()中数组中的 第一个数据
comments: res[1],
comments2: res[1].comments,
likeStatus: res[2].like_status,
likeCount: res[2].fav_nums
})
//隐藏Loading
wx.hideLoading()
})
}
})
①Promise.all等待所有子promise全部执行完成后才会触发.then的回调函数;
②Promise.race任何一个子promise率先完成就立即触发回调函数,不会去等待其他子promise,当然回调函数中的res将返回竞争成功的函数结果;
③举个例子:假设有三个子promise,调用时间分别为1.5s、2.5s、1s,如果用Promise.all(),那执行时间为2.5s,因为Promise.all()会等待所有子promise全部执行完毕才会触发回调函数;但是如果用Promise.race,那在拿到最快的子promise后就直接触发回调函数,不会去等待其他子promise
综上:promise.race的运用场景不多,更多的是使用Promise.all去解决实际问题
以上就是全部