Promise是ES6中的函数,规范了如何处理异步任务的回调函数,功能类似于jQuery的defferred。简单说就是通过promise对象的不同状态调用不同的回调函数。目前IE8及以下不支持,其他浏览器都支持。
promise对象的状态,从Pending转换为Resolved或Rejected之后,这个promise对象的状态就不会再发生任何变化。
使用步骤:
var promise = new Promise(function(resolve, reject) { // 异步任务,通过调用resolve(value) 或 reject(error),以改变promise对象的状态;改变状态的方法只能在此调用。//promise状态改变后,会调用对应的回调方法});promise.then(function(value){//resolve时的回调函数,参数由异步的函数传进来}).catch(function(error){//发生异常时或明确reject()时的回调函数})
具体使用:
function getURL(URL) { //因为promise创建时即执行,所以用工厂函数封装promise对象 return new Promise(function (resolve, reject) { var req = new XMLHttpRequest(); req.open('GET', URL, true); req.onload = function () { if (req.status === 200) { resolve(req.responseText); } else { reject(new Error(req.statusText)); } }; req.onerror = function () { reject(new Error(req.statusText)); }; req.send(); });}// 运行示例var URL = "http://httpbin.org/get";getURL(URL).then(function onFulfilled(value){ console.log(value);}).catch(function onRejected(error){ console.error(error);});
Promise的回调只有异步方式,即使是同步任务的回调也是异步执行 。
var promise = new Promise(function (resolve){ console.log("inner promise"); // 执行1:同步任务先执行 resolve(‘callBack');});promise.then(function(value){ console.log(value); // 执行3:虽然注册时状态为resolved,但回调仍是异步的;});console.log("outer promise"); // 执行2:同步代码先执行
promise的方法链
then方法注册的回调会依次被调用,每个then方法之间通过return 返回值传递参数。但是回调中的异常会导致跳过之间then的回调,直接调用catch的回调,之后再继续调用剩下的then的回调。在then(onFulfilled, onRejected)中,onFulfilled的异常不会被自己的onRejected捕获,所以优先使用catch。
promise .then(taskA) .then(taskB) .catch(onRejected) .then(finalTask);
taskA抛异常,taskB被跳过,finalTask仍会被调用,因为catch返回的promise对象的状态为resolved。
then方法内可以返回3种值
1. 返回另一个promise对象,下一个then方法根据其状态选择onFullfilled/onRejected回调函数执行,参数仍由新promise的resolv/reject方法传递;
2. 返回一个同步值,下一个then方法沿用当前promise对象的状态,无需等异步任务结束会立即执行;实参为上一then的返回值;如果没有return,则默认返回undefined;
新闻热点
疑难解答
图片精选