欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Promise用法

程序员文章站 2022-07-02 22:52:52
...

使用方法

let checkLogin = function(){
    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 getUserInfo = ()=>{
    return new Promise((resolve,reject)=>{
        let userInfo = {
            userId: "100"
        }
        resolve(userInfo)
    })
}

checkLogin().then((res) => {
    if(res.status == 0){
        console.log('login success)
    }
}).catch((error) => {
    console.log(`error${error}`)
}).then((res2) => {
    console.log(`userId:${res2.userId}`)
})
或者
Promise.all([chenkLogin(),getUserInfo()]).then(([res1,res2]) => {
    console.log(`result1:${res1.result},result2:${res2.userId}`)
})

vue中使用

getLotteryNums:function(){
  let self = this;
  return new Promise((resolve,reject)=>{
    queryGetParams(global.api + "api/nums/user",{"x-access-token":global.token}).then(response => {
      if(response.data.code == 1){
        self.lotteryNums =  response.data.data;
        resolve(self.lotteryNums);
      }
    });
  })
}