1.javascript的单线程特性
在javascript中,所有的代码都是单线程的 因此所有的网络操作,浏览器事件,都必须是异步执行的,异步执行的逻辑是回调。function callback() { console.log('hello') } console.log('begin') setTimeout(callback, 1000) console.log('end')
运行结果:
begin end hello2.Promise对象
像上列,和ajax等,承诺会在将来执行的对象,统称为Promise对象。 Promise对象是ES6引入的,由浏览器来支持。function test(resolve, reject) { var timeOut = Math.random()*2 console.log('timeOut '+timeOut) setTimeout(function () { if(timeOut<1){ console.log('call resolve1()') resolve('200') } else{ console.log('call reject()') reject('timeOut') } },timeOut*1000) } var p1 = new Promise(test) var p2 = p1.then(function (result) { console.log('成功'+result) }) var p3 = p2.catch(function (result) { console.log('失败'+result) })
test是异步执行函数,由两个参数resolve,reject,执行成功调用resolve,执行失败调用reject
我们不关心resole,reject具体是怎么执行的。new Promise(test)用来执行异步函数,并在将来某一时刻获取执行成功,或失败的结果
test函数执行成功,通过Promise对象 p1.then(function (result) { console.log('成功'+result) }) test函数执行失败,通知Promise对象 p2.catch(function (reason) { console.log('失败:' + reason); }); 可以将上述代码串联起来:new Promise(test).then(function (result) { console.log('成功:' + result);}).catch(function (reason) { console.log('失败:' + reason);});
3.ajax改写
function ajax(method, url, data) { var request = new XMLHttpRequest(); return new Promise(function (resolve, reject) { request.onreadystatechange = function () { if (request.readyState === 4) { if (request.status === 200) { resolve(request.responseText); } else { reject(request.status); } } }; request.open(method, url); request.send(data); });}var log = document.getElementById('test-promise-ajax-result');var p = ajax('GET', '/api/categories');p.then(function (text) { // 如果AJAX成功,获得响应内容 log.innerText = text;}).catch(function (status) { // 如果AJAX失败,获得响应代码 log.innerText = 'ERROR: ' + status;});
4.串行执行异步任务
job1.then(job2).then(job3).catch(handleError);
job1,job2,job3都是Promise对象
5.并行执行异步任务
多任务都执行完毕后,执行成功回调var p1 = new Promise(function (resolve, reject) { setTimeout(resolve, 500, 'P1');});var p2 = new Promise(function (resolve, reject) { setTimeout(resolve, 600, 'P2');});// 同时执行p1和p2,并在它们都完成后执行then:Promise.all([p1, p2]).then(function (results) { console.log(results); // 获得一个Array: ['P1', 'P2']});
多任务只要有一个执行完毕,执行成功回调
var p1 = new Promise(function (resolve, reject) { setTimeout(resolve, 500, 'P1');});var p2 = new Promise(function (resolve, reject) { setTimeout(resolve, 600, 'P2');});Promise.race([p1, p2]).then(function (result) { console.log(result); // 'P1'});