这篇文章主要介绍了关于es6 promise中then与catch的返回值的实例,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
故then方法与catch方法均会返回一个Promise对象(对,即使return 为某个值,或者throw error,或者不返回值)
我们来看看MDN的定义,这里可能为了严谨而说得有点乱七八糟的![1531105565214915.png 2391029044-5b40aad37ae52_articlex[1].png](https://img.php.cn//upload/image/604/554/163/1531105565214915.png)
简单来说,就是分为return 值(无return的情况下即返回undefined,也是返回值),throw error, return Promise
返回的Promise会成为Fulfilled状态。
return的值会作为新Promise对象下一个then的回调函数的参数值,贴代码看例子
var example = new Promise((fulfill, reject)=>{
let i = 1;
fulfill(i);
})
example
.then((value)=>{ console.log(value); value++; return value; })
.then((value) => {console.log(value); });输出结果如下:![1531105579954813.png 1689940441-5b40aaea912dc_articlex[1].png](https://img.php.cn//upload/image/779/418/485/1531105579954813.png)
调用fufill函数return value会传给下一个回调函数
回到上面的疑问,如果没有return呢,那么就会返回undefined
(就是函数无return返回的是undefined的情况,基础要扎实啊啊啊)
var example = new Promise((fulfill, reject)=>{
let i = 1;
fulfill(i);
})
example
.then((value)=>{ console.log(value); value++; })
.then((value) => {console.log(value);});输出结果如下:![1531105589835246.png 2156426177-5b40aafad4116_articlex[1].png](https://img.php.cn//upload/image/567/882/574/1531105589835246.png)
返回的Promise会成为Rejected状态,下一步执行catch中的回调函数或者then的第二个回调函数参数
这里出现了之前一直搞混的东西。
再次重复这一句话:catch为then的语法糖,它是then(null, rejection)的别名。
也就是说,catch也是then,它用于捕获错误,它的参数也就是是then的第二个参数。
所以,假设catch中如果return 值的话,新的Promise对象也会是接受状态。
看看例子:
var example = new Promise((fulfill, reject)=>{
let i = 1;
reject(i);
})
example
.catch(()=>{console.log('我是第一个catch的回调函数'); return 1;})
.then(() =>{console.log('我是第一个then的回调函数'); throw Error })
.catch(()=>{console.log('我是第二个catch的回调函数')})
.then(() => {console.log('我是第二个then的回调函数')})结果如下图:![1531105600371427.png 3218797185-5b40b1cf33150_articlex[1].png](https://img.php.cn//upload/image/891/526/922/1531105600371427.png)
调用reject函数后,promise变为rejected状态,故执行第一个catch的回调函数
第一个catch的回调函数return 1,故执行第一个then的回调函数
第一个then的回调函数throw Error,故执行第二个catch的回调函数
第二个catch的回调函数ruturn undefined(如上文所言),故执行第二个then的回调函数
至于return Promise的情况下,其实同理啦,我只是刚开始接触Promise语法时感到不是很适应:竟然会自动为你生成Promise对象?!后来看了部分源码剖析后才大致知道为什么会这样子,链接也放下面吧
用新学的知识实践封了个读取<input type='file'>中图片的插件:
https://github.com/Joeoeoe/-i...
哪里写得不好大家指出啊哈哈
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
以上就是ES6 Promise中then与catch的返回值的实例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号