视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
Promise的基本使用方法教程
2020-11-27 20:03:08 责编:小采
文档


fulfilledrejected
resolvedrejected
numberout of range

catch的用法

我们继续调用 paramTest 方法举例
paramTest().then((number) => {
 console.log('resolved');
 console.log(number);
 console.log(data); //data为未定义
},(reason) => {
 console.log('rejected');
 console.log(reason);
}).catch((err) => {
 console.log(err);
})

catch 方法其实就是 .then(null, rejection) 的别名,也是用来处理失败失败的回调函数,但是还有一个作用:当 resolve 回调中如果出现错误了,不会堵塞,会执行 catch 中的回调。

all的用法

const p = Promise.all([p1, p2, p3]);

p.then(result => {
 console.log(result);
})
all 方法接收一个数组参数,数组中每一项返回的都是 Promise 对象,只有当 p1, p2, p3 都执行完才会进入 then 回调。p1, p2, p3 返回的数据会以一个数组的形式传到 then 回调中。
const p1 = new Promise((resolve, reject) => {
 setTimeout(() => {
 resolve('p1');
 }, 1000);
})
.then(result => result)
.catch(e => e);

const p2 = new Promise((resolve, reject) => {
 setTimeout(() => {
 resolve('p2');
 }, 3000);
})
.then(result => result)
.catch(e => e);

Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
//3秒后
输出['p1', 'p2']

race的用法

const p = Promise.race([p1, p2, p3]);

p.then(result => {
 console.log(result);
})
race 的用法与 all 如出一辙,不同的是 all 方法需要参数的每一项都返回成功了才会执行 then;而 race 则是只要参数中的某一项返回成功就执行 then 回调。

以下是 race 的例子,和 all 方法对比,可以看到返回值有很明显的区别。

const p1 = new Promise((resolve, reject) => {
 setTimeout(() => {
 resolve('p1');
 }, 1000);
})
.then(result => result)
.catch(e => e);

const p2 = new Promise((resolve, reject) => {
 setTimeout(() => {
 resolve('p2');
 }, 3000);
})
.then(result => result)
.catch(e => e);

Promise.race([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
//1秒后
输出 'p1'

点击这里查看本文中实例源代码

resloader是基于Promise实现的一个图片预加载并展示加载进度的插件,猛戳这里了解详情。如果感觉还可以的话,欢迎star

相关推荐:

使用Promise简化回调

微信小程序Promise简化回调实例分享

jQuery的Promise如何正确使用

下载本文
显示全文
专题