(1) .then 得到异步任务的正确结果 (2) .catch 获取异常信息 (3) .finally 成功与失败都

时间:2022-04-19 02:18:22

  (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(‘:3000/a1‘); var p2 = queryData(‘:3000/a2‘); var p3 = queryData(‘: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(‘:3000/a1‘); var p2 = queryData(‘:3000/a2‘); var p3 = queryData(‘:3000/a3‘); Promise.race([p1, p2, p3]).then((data) => console.log(data));

  

  

Promise常用的API

标签:

原文地点:https://www.cnblogs.com/Alisa-k/p/12672870.html