美文网首页
2019-07-24-new-promise-造成异步结果

2019-07-24-new-promise-造成异步结果

作者: xiaojianxu | 来源:发表于2019-07-25 11:27 被阅读0次

    如代码所示,父组件中,调用子组件(this.$refs.assignForm)的 方法 getData。

    this.$refs.assignForm.getData() 方法,返回的是 promise - resolve。

    Promise 简介
    Promise-Introduce
    Using Promise

    The Promise object represents the eventual completion (or failure) of an 
    asynchronous operation, and its resulting value.
    

    问题:发现怎么都无法在 getData() 后面代码中,得到想要的数据。

    image.png

    Line 105 行,代码调试输出的数据,为正确的数据。
    Line 107 行,代码调试输出的数据,却是非正确数据。

    调试了很久,一直以为是与 watch 有关。最后才发现,这是由于 Promise 的特点所导致的。

    Promise 的特点是异步操作,那么所有基于 Promise 的返回数据,进行操作的代码,都应该在 Promise 内执行。


    总结:

    - 不知道 Promise 的特性;
    - 观察调试输出现象不仔细,如:Line 107 打印是在 console 中先输出的,再然后是 Line 105 输出的;
    

    *** 前面两项因素加在一起,导致的结果就是毫无方向感地乱撞,浪费了时间、精力,以及人也变焦虑了。***


    父组件代码

    async handelSubmit () {
          this.$refs.assignForm.getData().then(value => {
            if (value) {
              this.assignModel = value
            }
            // Line: 105 调试输出 #1 
            console.log(this.assignModel, value)
          })
          // Line: 107 调试输出 #2
          console.log(this.assignModel)
          var formData = []
          for (var key in this.data.config) {
            let item = this.data.config[key]
            formData[key] = { name: item.name, content: this.template[item.key] }
          }
    

    子组件代码

    getData () {
          return new Promise((resolve, reject) => {
            resolve(this.assignModel)
          })
        }
    

    相关文章

      网友评论

          本文标题:2019-07-24-new-promise-造成异步结果

          本文链接:https://www.haomeiwen.com/subject/lqlfrctx.html