zoukankan      html  css  js  c++  java
  • Promise链式回调的使用



    /*Promise通常配合then方法来链式的使用,then方法里面第一个回调函数表示成功状态,也就是resolve,第二个是失败状态-reject,如果默认写一个参数的话,默认resolve*/

    
    
    let checkLogin=()=> {
      return new Promise((resolve,reject)=>{
        let flag=document.cookie.indexOf("userId")!=-1?true:false;
        if(flag=true){
          resolve({
            status:0,
            result:true
          });
        }else{
          reject("error");
        }
      });
    }
    let getuseInfo=()=>{
      return new Promise((resolve,reject)=>{
        let useInfo={
          status:0,
          userId:101
        }
        resolve(useInfo);
      })
    }
    
    checkLogin().then((res)=>{
      console.log("Login Success");
      return getuseInfo();
    },(error)=>{
      console.log(`error:${error}`);
    }).then(res=>{
      console.log(`userId:${res.userId}`);
    });
    
    
    //Promise.all()的使用
    Promise.all([checkLogin(),getuseInfo()]).then(([res1,res2])=>{
      console.log("Login Success");
      console.log(`userId:${res2.userId}`);
    })
    

    Promise.all(requestPromises).then(...).catch(...) 会在所有requestPromises都resolve时才会进then方法,并且把所有结果以一个数组返回。只要有一个失败,就会进catch。如果在单个请求中定义了catch方法,那么就不会进Promise.all的catch方法。

  • 相关阅读:
    TinySpider开源喽
    TinyXmlParser开源喽
    Tiny快速入门之控制层开发
    TinyDBRouter
    TinyIOC
    开源前要做好哪些准备工作?
    分布式锁的简单实现
    TinyDBCluster Vs routing4db
    HTML5基础(五)
    HTML5基础(四)
  • 原文地址:https://www.cnblogs.com/wangxirui/p/9029343.html
Copyright © 2011-2022 走看看