美文网首页
promise常用的API

promise常用的API

作者: 小黄不头秃 | 来源:发表于2023-06-07 01:28 被阅读0次
<!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>
    <!-- 
        实例方法:
        p.then()得到异步任务的正确结果
        p.catch()获取异常信息
        p.finally()成功与否都会执行
     -->

     <!-- 
         对象方法:
         Promise.all()并发处理多个异步任务,所有的任务都执行完成才能得到结果
         Promise.race()并发处理多个异步任务,只要有一个任务完成就能得到结果
      -->
     <script>
         function foo(){
             return new Promise(
                 function(resolve,reject){
                     setTimeout(function(){
                         resolve(123);
                        // reject("error");
                     },100);
                 }
             );
         }
         foo()
            .then(function(data){
                console.log(data);
            })
            .catch(function(data){
                console.log(data);
            })
            .finally(function(){
                console.log("finally");
            })

            var p1 = foo();
            var p2 = foo();
            var p3 = foo();

            Promise.all([p1,p2,p3]).then(function(ret){
                console.log("all: "+ret);
            });
            Promise.race([p1,p2,p3]).then(function(ret){
                console.log("race: "+ret);
            });
     </script>
</body>
</html>

相关文章

网友评论

      本文标题:promise常用的API

      本文链接:https://www.haomeiwen.com/subject/uhlpedtx.html