专业的编程技术博客社区

网站首页 > 博客文章 正文

Promise中的all, race, allSettled, any的区别

baijin 2024-08-14 11:57:15 博客文章 5 ℃ 0 评论


race和any的区别: race就讲快,我数学算得特别快,2341*465654等于多少?等于8. OK,你真的快,快就行,快就返回,返回是对的就走then,错的就走catch. any不一样,比较耐心,第一个不对,试试第二个,第二个不行,试第三个,如果有对的就返回走then,如果第三个还不对,试试第四个,如果所有的都不对,返回,走catch

all所有都成功,返回走then,只要有一个失败,就返回走catch


一般的用法:

<!DOCTYPE html>

<html lang="en">


<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

</head>


<body>

<script>

function ajax(url) {

return new Promise((resolve, reject) => {

let xhr = new XMLHttpRequest();

xhr.open("get", url);

xhr.send();

xhr.onreadystatechange = function () {

if (xhr.readyState == 4) {

if (xhr.status >= 200 && xhr.status < 300) {

resolve(xhr.responseText);

} else {

reject(xhr.responseText);

}

}

}

});

}


ajax("1.json")

.then((res) => {

console.log('res:', JSON.parse(res));

})

.catch((err) => {

console.log('err:', err);

})

</script>

</body>


</html>

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表