Promises
从 ECMAScript 6 开始,JavaScript 增加了对 Promise
对象的支持,它允许你对延时和异步操作流进行控制。
Promise
对象有以下几种状态:
- pending:初始的状态,即正在执行,不处于 fulfilled 或 rejected 状态。
- fulfilled:成功的完成了操作。
- rejected:失败,没有完成操作。
- settled:Promise 处于 fulfilled 或 rejected 二者中的任意一个状态, 不会是 pending。
详细说明:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise
function imgLoad(url) { return new Promise(function(resolve, reject) { var request = new XMLHttpRequest(); request.open('GET', url); request.responseType = 'blob'; request.onload = function() { if (request.status === 200) { resolve(request.response); } else { reject(Error('Image didn\'t load successfully; error code:' + request.statusText)); } }; request.onerror = function() { reject(Error('There was a network error.')); }; request.send(); }); }
简化:
function myAsyncFunction(url) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.onload = () => resolve(xhr.responseText); xhr.onerror = () => reject(xhr.statusText); xhr.send(); }); };
const promise1 = new Promise((resolve, reject) => { setTimeout(() => { resolve('foo'); }, 300); }); promise1.then((value) => { console.log(value); // expected output: "foo" }); console.log(promise1); // expected output: [object Promise]
base:
let myFirstPromise = new Promise(function(resolve, reject){ //当异步代码执行成功时,我们才会调用resolve(...), 当异步代码失败时就会调用reject(...) //在本例中,我们使用setTimeout(...)来模拟异步代码,实际编码时可能是XHR请求或是HTML5的一些API方法. setTimeout(function(){ resolve("成功!"); //代码正常执行! }, 250); }); myFirstPromise.then(function(successMessage){ //successMessage的值是上面调用resolve(...)方法传入的值. //successMessage参数不一定非要是字符串类型,这里只是举个例子 console.log("Yay! " + successMessage); });
————————————————————————
让科技和智能使人更便捷 --- 从我做起
————————————————————————