具体文章解释请看廖雪峰老师的文章,这里仅仅记录笔记。国内飞机票点击访问
首次接触可能一脸懵逼,下面的代码手把手敲一遍,100%懂。
(1).基础demo
//创建承诺 let p1 = new Promise(function (resolve, reject) { //生成随机数 var timeout = Math.random() * 2; //延迟执行 setTimeout(() => { if (timeout < 1) { //小于1成功 resolve(`success:${timeout}`); } else { //否则失败 reject(`failed:${timeout}`); } }, timeout * 1000); }); //调用承诺,当承诺成功才执行.then回调 let p2 = p1.then(function (result) { console.log(result); }); //调用承诺,当承诺失败才执行.then回调 let p3 = p2.catch(function (reason) { console.log(reason); });
(2).then和catch可以串联起来,上面的写法只是为了告诉你then和catch返回的还是promise对象
let p2 = p1.then(function (result) { console.log(result); }).catch(function (reason) { console.log(reason); });
(3).Promise是如何异步执行的(异步执行的流程中,把执行代码和处理结果的代码清晰地分离)
//获取元素节点 let logging = document.getElementById('logArea'); //显示日志到dom区域 function log(s) { var p = document.createElement('p'); p.innerHTML = s; logging.appendChild(p); } //创建承诺 let p1 = new Promise(function (resolve, reject) { log('start new Promise...'); var timeOut = Math.random() * 2; log('set timeout to: ' + timeOut + ' seconds.'); setTimeout(function () { if (timeOut < 1) { log('call resolve()...'); resolve('200 OK'); } else { log('call reject()...'); reject('timeout in ' + timeOut + ' seconds.'); } }, timeOut * 1000); }).then(function (result) { log('Done: ' + result); }).catch(function (reason) { log('Failed: ' + reason); });
(4).多个异步任务依赖,例如先ajax请求第一个接口,再去请求第二个接口,再去请求第三个接口,将三个接口的值相加,严格按接口1,接口2,接口3的顺序执行
//模拟请求接口1,后端返回数字50, var api1 = function(num){ return new Promise(function(resolve){ setTimeout(() => { console.log('接口1的数值拿到了,开始去第二个接口拿值'); resolve(50+num) }, 5000); }); } //模拟请求接口2,后端返回数字60, var api2 = function(num){ return new Promise(function(resolve){ setTimeout(() => { console.log('接口2的数值拿到了,开始去第三个接口拿值'); resolve(60+num) }, 2000); }); } //模拟请求接口3,后端返回数字60, var api3 = function(num){ return new Promise(function(resolve){ setTimeout(() => { console.log('接口3的数值拿到了,开始去第二个接口拿值'); resolve(60+num) }, 1000); }); } //创建承诺 let p1 = new Promise(function(resolve){ resolve(0); }); p1.then(api1).then(api2).then(api3).then(function(result){ console.log(`3个接口返回的值合计:${result}`); });
(5).并发请求,同时请求2个接口,将结果集合并
//用户信息接口 var userApi = new Promise(function(resolve){ resolve({'userId':'18326'}); }); //用户资产接口 var userAssetApi = new Promise(function(resolve){ resolve({'money':10000000}); }); //并发请求2个接口,2个接口的返回值合并在一起 Promise.all([userApi,userAssetApi]).then(function(result){ console.log(result); });
(6).异步任务容错,例如为了保证某个接口高可用,我们在2个服务器部署这个接口,前端ajax请求2个接口,那个先返回就使用那个,避免有接口不可用。
//用户信息接口.服务器1 var userApi1 = new Promise(function(resolve){ setTimeout(() => { resolve({'userId':'18326 from server1'}); }, 2000); }); //用户信息接口.服务器2 var userApi2 = new Promise(function(resolve){ resolve({'userId':'18326 from server2'}); }); //并发请求2个接口,那个先返回就先用那个,后返回的直接抛弃掉 Promise.race([userApi1,userApi2]).then(function(result){ console.log(result); });