Promise 用法

Promise 用法

promise 是 ES6 中用于解决因异步而产生顺序错误问题的方法。

为什么要用Promise?

举个简答的例子:

比如说,你要发一个请求来获取所有 Person 对象,

每个 Person 对象中有一个字段 perId,

fn_getPerson(){
	this.axios.get('/person').then(res=>{
        console.log(res.data)  // 返回Person对象:Person:{ perId:1 } 
    })
}

然后根据 perId 接着请求与 Person 关联的 Hospital。

fn_getHospital(perId){
    this.axios.post('/hospital',{
        perId:perId
    }).then(res=>{
        console.log(res.data)	
        // 返回与 perId 绑定的 Hospital 对象:Hospital:{ hosId:1, room:"G107" } 
    })
}

这个时候,你就要用到 Promise了。

像上面说的情况,如果你不用Promise。

可能会出现以下情况:

perId 还未获取到,就进行了 fn_getHospital(perId),此时的 perId 为 undefined,所以肯定会出错。

基于Vue的Promise例子

<template>
  <div>
    <el-button @click="fn_noPromise">no promise</el-button>
    {{data_noPromise}}
    <br />
    <el-button @click="fn_usePromise">use promise</el-button>
    {{data_usePromise}}
  </div>
</template>

<script>
export default {
  data() {
    return {
      data_noPromise: undefined,
      data_usePromise: undefined
    };
  },
  methods: {
    fn_noPromise() {
      this.data_noPromise = "";
      setTimeout(() => {
        this.data_noPromise += "1  ";
      }, 1000);
      this.data_noPromise += "2   ";
    },
    fn_usePromise() {
      let _this = this;
      this.data_usePromise = "";
      let fn_promise = () => {
        return new Promise(resolve => {
          setTimeout(() => {
            _this.data_usePromise += "1  ";
            resolve();
          }, 1000);
        });
      };
      fn_promise().then(() => {
        _this.data_usePromise += "2   ";
      });
    }
  }
};
</script>

代码是基于vue的,不会vue的看看也不会很难理解,以下是运行的结果

在这里插入图片描述

这里用 setTimeout 函数来设置一个延时来模拟请求。

可以发现,

没有使用promise的情况下,2会直接忽略1的延时进行输出;

有promise的情况,2会等待1发送resolve信息后,再执行。

这就是promise……这就是为了防止因异步而产生顺序错乱的promise,它给了你承诺!

猜你喜欢

转载自blog.csdn.net/qq_41297145/article/details/106180107
今日推荐