Promise常用的API
1、实例方法
(1).then 得到异步任务的正确结果
(2).catch 获取异常信息
(3).finally 成功与失败都会执行
<script> function foo() { return new Promise(function(resolve, reject) { // resolve('成功'); reject('失败') }) } // ----------------------------------------- 方法一 foo() .then(function(data) { console.log('then'); }) .catch(function(data) { console.log('catch'); }) .finally(function(data) { console.log('finally'); }) // ----------------------------------------- 方法二 foo() .then(function(data) { console.log('then'); }, function(data) { console.log(data); }) .finally(function(data) { console.log('finally'); }) </script>
2、对象方法
(1)Promise.all() 并发处理多个异步任务,所有任务都能执行完成才能得到结果
function queryData(url) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState != 4) { return; } if (xhr.readyState == 4 && xhr.status == 200) { resolve(xhr.responseText); } else { reject('服务器错误'); } }; xhr.open('get', url); xhr.send(); }); } var p1 = queryData('http://localhost:3000/a1'); var p2 = queryData('http://localhost:3000/a2'); var p3 = queryData('http://localhost:3000/a3'); Promise.all([p1, p2, p3]).then((data) => console.log(data));
(2)Promise.race() 并发处理多个异步任务,只要有一个任务完成就能得到结果
function queryData(url) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState != 4) { return; } if (xhr.readyState == 4 && xhr.status == 200) { resolve(xhr.responseText); } else { reject('服务器错误'); } }; xhr.open('get', url); xhr.send(); }); } var p1 = queryData('http://localhost:3000/a1'); var p2 = queryData('http://localhost:3000/a2'); var p3 = queryData('http://localhost:3000/a3'); Promise.race([p1, p2, p3]).then((data) => console.log(data));