在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML/ vue中使用 promise在computed和methods的區(qū)別

vue中使用 promise在computed和methods的區(qū)別

問(wèn)題:定義了一個(gè)api
里面返回一個(gè)Promise

export function fetchPost(url, var1) {
  return new Promise((resolve, reject) => {
    axios.post(url, qs.stringify(var1)).then(res => {
      resolve(res.data)
    }).catch(res => {
      reject(res)
    })
  })
}

然后在vue組件中定義了computed屬性

    computed: {
      article: async function () {
        let id = this.$route.params.id;
        let obj = await getDescribe(id);
        console.log(obj.tLists[0]);
        return obj.tLists[0];
      }
    },

但是在頁(yè)面中顯示article時(shí)promise

clipboard.png

但是如果不使用computed而使用methods+mounted生命鉤子來(lái)完成

    methods: {
      async getArticle() {
        let id = this.$route.params.id;
        let obj = await getDescribe(id);
        this.article = obj.tLists[0];
      }
    },
    mounted() {
      this.getArticle()
    }

clipboard.png

可以看到article會(huì)變成正常的object
這是什么原因?qū)е碌?希望可以解惑

回答
編輯回答
傲寒

async function中的返回值是用于后續(xù)異步操作的,并不是其本身的返回值。調(diào)用該函數(shù)時(shí),會(huì)立即返回一個(gè)Promise對(duì)象。

async function firstJob() {
  var result1 = await someAsyncTask();
  var result2 = await anotherAsyncTask(result1);
  return result2;
}
console(firstJob()); // 返回Promise

firstJob().then(function (result){
  console.log(result); // 返回result2的值
});

computed計(jì)算變量的結(jié)果是直接取的function的返回值,不會(huì)考慮該function是否為異步,所以每次計(jì)算結(jié)果article都是一個(gè)Promise對(duì)象。watch里面的代碼還是會(huì)執(zhí)行完的,只不過(guò)obj.tLists[0]值并沒(méi)有作為其方法返回的值附給article。

methods中的getArticle方法里有this.article = obj.tLists[0]這句,所以article在異步執(zhí)行到這句話的時(shí)候就會(huì)被賦值。

如果要監(jiān)聽this.$route.params.id的變化來(lái)異步修改article,建議用watch。

2018年1月8日 17:54