• promise思考


    我写了三个单元块,分别对应三种业务场景

    let query;
    query = (url) => {
    url=url||"传递的参数为空";
    return new Promise((resolve,reject) => {
    setTimeout(() => {
    console.log(url);
    if(true){
    resolve("我是promise执行后传递过来的数据");
    }else{
    reject();
    }

    }, 3000)
    }).catch((error)=>{console.log(error)});
    };
    //基本链式调用
    //直接传入query会取上一个promise传递过来的参数,使用()=>query()会传递空参数,其他的就传递相应的参数
    function basicChain(){
    query("test1")
    .then(query)
    .then(()=>"then 传递的参数")
    .then((data)=>query(data))
    .then(()=>query())
    .then(()=>query("test2"))
    .then(()=>query("test3"))
    }

    //按照一定顺序循环调用
    function loopChain(){
    let queryloop=Promise.resolve(0);
    for(let j=0;j<10;j++){
    queryloop=queryloop.then(()=>query("test"+j));
    }
    }

    //无顺序执行promise;
    function unsortChain(){
    let arrCreate=()=>{
    let arr=[];
    for(let i=1;i<11;i++){
    arr.push(query("test"+i));
    }
    return arr;
    }
    let arr=arrCreate();
    Promise.all(arr)
    .then(()=>{console.log("promise 全部执行了")})
    .catch(function(error){console.log(error)});
    }

    登录小逻辑
    <script>
            let status = 1;
            let userLogin = (resolve, reject) =>{
                setTimeout(()=>{
                    if(status == 1){
                        resolve({data:'登录成功', msg:'xxx', token:'xxsadfsadfas'});
                    }else{
                        reject('失败了');
                    }
                },2000);
            };
    
            let getUserInfo = (resolve, reject) =>{
                setTimeout(()=>{
                    if(status == 1){
                        resolve({data:'获取用户信息成功', msg:'asdfasdf', token:'xxsadfsadfas'});
                    }else{
                        reject('失败了');
                    }
                },1000);
            }
    
            new Promise(userLogin).then(res=>{
                console.log('用户登录成功');
                return new Promise(getUserInfo);
            }).then(res=>{
                console.log('获取用户信息成功');
                console.log(res);
            })
        </script>

      

    学而不思则罔,思而不结则殆,结而不看,一事无成
  • 相关阅读:
    【cf1247E】E. Rock Is Push(dp+二分)
    【cf1245F】F. Daniel and Spring Cleaning(数位dp)
    【cf1243D】D.0-1 MST(set+均摊复杂度分析)
    [CF1201D] Treasure Hunting
    [CF1211C] Ice Cream
    [CF1213E] Two Small Strings
    [CF1219G] Harvester
    [CF1223D] Sequence Sorting
    [CF1231E] Middle-Out
    [CF1244E] Minimizing Difference
  • 原文地址:https://www.cnblogs.com/windseek/p/7650989.html
Copyright © 2020-2023  润新知