Promise.prototype.then()和Promise.prototype.catch()
来源:互联网 发布:男发型设计软件下载 编辑:程序博客网 时间:2024/05/21 10:28
Promise.prototype.then()
Promise实例具有then
方法,也就是说,then
方法是定义在原型对象Promise.prototype上的。它的作用是为Promise实例添加状态改变时的回调函数。
then
方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。因此可以采用链式写法,即then
方法后面再调用另一个then
方法。
getJSON('/posts.json').then(function(json){ return json.post;}).then(function(){ // ...});
上面的代码使用then
方法,依次指定了两个回调函数。第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。
采用链式的then
,可以指定一组按照次序调用的回调函数。
getJSON('/post/1.json').then(function(post){ return getJSON(post.commentURL);}).then(function funcA(comments){ console.log('Resolved:',comments);}, function funB(err){ console.log('Rejected:',err);});
上面代码中,第一个then
烦烦烦指定的回调函数,返回的是另一个Promise对象。这时,第二个then
方法指定的回调函数,就会等待新的Promise对象状态发生变化。
如果变为Resolved,就调用funcA
,如果状态变为Rejected,就调用funcB
。
如果采用箭头函数,上面的代码可以写的更简洁:
getJSON('/post/1.json').then( post=>getJSON(post.commentURL)).then( commnets=>console.log('Resolved:',comments), err=>console.log('Rejected:',err));
Promise.prototype.catch()
Promise.prototype.catch
方法是.then(null,rejeaction)
的别名,用于指定发生错误时的回调函数。
getJSON('/posts.json').then(function(posts){ // ...}).catch(function(error){ // 处理getJSON和前一个回调函数运行时发生的错误 console.log(error);});
0 0
- Promise.prototype.then()和Promise.prototype.catch()
- Promise.prototype.catch()
- promise then catch
- 对Promise.resolve(),Promise.reject(),Promise.prototype.then()的初步了解
- promise.done和promise.then的区别
- 关于Promise.then()的思考
- promise
- Promise
- Promise
- Promise
- Promise
- Promise
- Promise
- promise
- promise
- promise
- promise
- Promise
- appium 如何定位webview元素
- MYSQL开启远程连接和关闭远程连接
- SmartImageView
- Linux下chkconfig命令详解
- 强大的Spring缓存技术(中)
- Promise.prototype.then()和Promise.prototype.catch()
- 旋转数组的最小数字
- 使用比较器实现list排序
- 强大的Spring缓存技术(下)
- 使用js将img转换为base64
- SODBASE数据输出适配器----HTTP请求
- JSON解析的几种方式
- C# 中文字符比较 or C#汉字比较 or C# 中文字符串比较 or C#中文名字比较
- Redis学习笔记(六)redis实现分布式锁