Vue Promise async await

Promise 是什么
Promise 有三种状态
pending:等待中,或者进行中,表示还没有得到结果
resolved:已经完成,表示得到了我们想要的结果,可以继续往下执行
rejected:也表示得到结果,但是由于结果并非我们所愿,因此拒绝执(用catch捕获异常)

Vue 异步函数 async 和 await
async 和 await 基于 promise 的。 使用 async 的函数将会始终返回一个 promise 对象;
async:作为一个关键字放到函数前面,用于表示函数是一个异步函数;
await:等待;

Promise 简单用法

function2(){
    // 你的逻辑代码 
    return Promise.resolve(/* 这里是需要返回的数据*/)
}

function3(){
    // 你的逻辑代码 
    return Promise.resolve(/* 这里是需要返回的数据*/)
}

function test1(num) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(2 * num)
        }, 2000);
    } )
}

// 调用
function1(){
    this.function2().then(val => { 
        this.function3();
    })
    .catch(err => {
      console.error(err)
      console.log('Ln 297 出错了')
    });
}

Promise 高级用法

init1(){
return new Promise((resolve, reject) => {
    let data={
        dateStr:this.time
    };
    api.get('url', null).then( res => {
       //自己的操作
        resolve()
    }).catch(err => {
        reject()
    });
});
};
init2(){
return new Promise((resolve, reject) => {
    let data={
        dateStr:this.time
    };
    api.get('url', null).then( res => {
       //自己的操作
        resolve()
    }).catch(err => {
        reject()
    });
});
};


//调用
Promise.all([this.init1(),this.init2()]).then(() => {
    //两个都调成功以后执行的操作
//主要是loading问题
}).catch(err => {
    // 抛出错误信息
});

Promise 高级使用【vue element admin src/store/modules/user.js】

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      console.log(`/src/store/modules/user.js Ln 36`)
      login({ user_name: username.trim(), password: password }).then(response => {
        const { data } = response
        console.log(`/src/store/modules/user.js Ln 39 ${JSON.stringify(response)}`)
        console.log(`/src/store/modules/user.js Ln 40 ${JSON.stringify(data.access_token)}`)
        commit('SET_TOKEN', data.access_token)
        setToken(data.access_token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    console.log(`/src/store/modules/user.js Ln 52 ${state.token}`)
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        console.log(`/src/store/modules/user.js Ln 56 ${data}`)
        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

案例 ***.vue 文件

export default {
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        per_page: 10,
        department_code: '',
        room_code: '',
        doctor_code: '',
        queue_state: 1,
        invalid: 0
      },
      queueState: 'inLine',
    }
  },
  watch: {},
  created() {
    this.getQueues()
    .then(val => { 
      this.setButtonDisable()
    })
    .catch(err => {
      console.error(err)
      console.log('Ln 297 出错了')
    })
  },
  mounted() {
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    async getQueues() {
      const res = await getQueues(this.listQuery)
      this.list = res.data.items
      this.total = res.data.total
      this.listLoading = false   
    }
  }
}

async 异步

async function timeout() {
  return 'hello world';
}

在 methods 中使用 async 函数

methods: {
  async login() {
    console.log(`异步函数`)
    const res = await fetch('https://raw.githubusercontent.com/DaKoala/fetch-example/master/people.json');
    const json = await res.json();
    const person = json[1];
    alert(`我是${person.name},我今年${person.age}岁。`);
  }
}

*
*
*
*
*

你可能感兴趣的:(Vue)