promise 是异步编程的一种解决方案,promise是一个对象,可以从他获取异步操作的消息。
(1)对象不受外界的影响。promise对象代表一个异步操作,有三种状态。pending(进行中),从pending到fulfilled(成功),从pending到rejected(失败)
(2)状态一旦改变就不会再改变,所以只有两种结果。
promise基本用法:
ES6规定,promise对象是一个构造函数,用来生成promise实例。
const promise = new Promise(function(resolve, reject) { if (/* 异步操作成功 */){ resolve(value); } else { reject(error); } });Promise实例生成以后,可以用then方法分别指定resolved状态和rejected状态的回调函数。
promise.then(function(value) { // success }, function(error) { // failure });promise 对象实现ajax:
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); });