Promise.prototype.then()和Promise.prototype.catch()
2016-12-21 12:06
369 查看
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); });
相关文章推荐
- 从零开始学_JavaScript_系列(49)——Promise(2)then、值、catch
- es6 Promise.prototype.then()方法
- es6 Promise.prototype.catch()方法
- 对Promise.resolve(),Promise.reject(),Promise.prototype.then()的初步了解
- 浅谈promise(then、catch、resolve、reject、race、all、done、finally)
- Promise.prototype.catch()
- promise then catch
- [javascript高手之路] es6系列教程 - promise常见用法详解(resolve,reject,catch,then,all,race)
- [js高手之路] es6系列教程 - promise常见用法详解(resolve,reject,catch,then,all,race)
- JS中Promise函数then的奥秘探究
- ES6中, Promise/then的用法, 躲坑秘籍
- iOS promisekit的使用 dispatch promise then then inbackground
- Promise重写confirm,alert弹出框 .then()
- 详解ES6 Promise对象then方法链式调用
- jquery 中的deffered和promise对象方法及$when done then的使用
- promise.then,process.nextTick, setTimeout 以及 setImmediate 的执行顺序
- Promise.then fired with only one argument?
- Promise.then
- 多线程,异步 boost::future::then, std::promise, std::async, std::future etc.
- 用gulp前段自动化构建工具的小心了,关于angular.js中取消success,error的功能,用then和.catch