手写Promise

2020-11-09  本文已影响0人  鱼香肉丝没有渔

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <button id="btn">摇数字1-8</button>
    <div></div>
    <script>
     var b = document.getElementById("btn");
     var div = document.querySelector('div');
     b.onclick = function (){
        var p = new Promise(function(resolve,reject){
                setTimeout(()=>{
                    let n = parseInt(Math.random()* 7 + 1,10);
                    resolve(n)
                },1000);        
            }); 
        p.then((x) =>{
            div.innerText ='数字是' + x
        },(err)=>{
            console.log('失败'+ err)
        });
      }
    </script>
</body>
</html>
<script>
    function 摇(){
        return new Promise(function(resolve,reject){
                setTimeout(()=>{
                    let n = parseInt(Math.random()* 7 + 1,10);
                    resolve(n)
                },1000);        
            }); 
        }
        摇().then(
            x =>{
            console.log('数字是' + x);
        },()=>{
            console.log('失败')
        });
    </script>

Promise.all

  Promise.all([
    $.ajax({url:'data/arr.txt',dataType:'json'}),
    $.ajax({url:'data/json.txt',dataType:'json'}),
]).then((results)=>{
  let [arr,json] = results;
 alert('成功')
}),()=>alert('失败')




上一篇下一篇

猜你喜欢

热点阅读