Promise是一个类,能够建立实例;【表明承诺,何时会用到承诺,通常是异步任务,就是须要很长时间执行任务(先画个饼)】json
Promise构造函数接受一个函数做为参数,该函数的两个参数分别是resolve和reject。它们是两个函数,由 JavaScript 引擎提供,不用本身部署。promise
new promise = New Promise(function(resolve,reject){ if(异步操做成功){ resolve(value) }else{ reject(error) } })
Promise实例生成之后,能够用then方法分别指定resolved状态和rejected状态的回调函数。app
promise.then(function(value) { // success }, function(error) { // failure });
then方法能够接受两个回调函数做为参数。异步
function loadImageAsync(url) { return new Promise(function(resolve, reject) { const image = new Image(); image.onload = function() { resolve(image); }; image.onerror = function() { reject(new Error('Could not load image at ' + url)); }; image.src = url; }); }
const getJSON = function(url) { const promise = new Promise(function(resolve, reject){ const handler = function() { if (this.readyState !== 4) { return; } if (this.status === 200) { resolve(this.response); } else { reject(new Error(this.statusText)); } }; const client = new XMLHttpRequest(); client.open("GET", url); client.onreadystatechange = handler; client.responseType = "json"; client.setRequestHeader("Accept", "application/json"); client.send(); }); return promise; }; getJSON("/posts.json").then(function(json) { console.log('Contents: ' + json); }, function(error) { console.error('出错了', error); });
Promise实列具备then方法【获取Promise成功的值或者失败的缘由】,能够说,then方法是定义在Promise对象的原型(prototype)上。函数
then方法返回的是一个新的Promise实例(注意,不是原来那个Promise实例)。所以能够采用链式写法,即then方法后面再调用另外一个then方法。post
getJSON("/posts.json").then(function(json) { return json.post; }).then(function(post) { // ... });
上面的代码使用then方法,依次指定了两个回调函数。第一个回调函数完成之后,返回一个全新的Promise对象,会将返回结果做为参数【这个参数就能够作为全新的Promise对象的then()中的参数】,传入第二个回调函数。this
采用链式的then,能够指定一组按照次序调用的回调函数。这时,**前一个回调函数,有可能返回的仍是一个Promise对象(即 有异步操做)**,这时**后一个回调函数,就会等待该Promise对象的状态发生变化,才会被调用。**
getJSON("/post/1.json").then(function(post) { return getJSON(post.commentURL); }).then(function (comments) { console.log("resolved: ", comments); }, function (err){ console.log("rejected: ", err); });
上面代码中,第一个then方法指定的回调函数,返回的是另外一个Promise对象。这时,第二个then方法指定的回调函数,就会等待这个新的Promise对象状态发生变化。若是变为resolved,就调用第一个回调函数,若是状态变为rejected,就调用第二个回调函数。url
getJSON('/posts.json').then(function(posts) { // ... }).catch(function(error) { // 处理 getJSON 和 前一个回调函数运行时发生的错误 console.log('发生错误!', error); });
上面代码中,getJSON方法返回一个 Promise 对象,若是该对象状态变为resolved,则会调用then方法指定的回调函数;若是异步操做抛出错误,状态就会变为rejected,就会调用catch方法指定的回调函数,处理这个错误。另外,then方法指定的回调函数,若是运行中抛出错误,也会被catch方法捕获。prototype