【问题标题】:Promise Chain Out of Order无序的承诺链
【发布时间】:2018-04-17 13:34:29
【问题描述】:

我最近遇到了 javascript 中的 Promise Chain 的问题,特别是在 Vue.js 中。 这是我的代码,我有一个 addItem 函数,可以在数据库中插入一个项目。我想让这个函数运行它在数据库中插入东西然后使用 getItems 函数来更新所有数据。但是,我发现这个函数会先运行 .then 中的东西,然后最后将项目插入数据库中。这导致我的代码中断。如果有人能帮助我,那就太好了!

  addItem: function() {
  this.$store.dispatch('addJournal',{
   journal: this.text,
   page: this.maxPage + 1, // increase the page number
    }).then(response => {
      this.text = ""; // set the input to empty
      this.getItems(); // get all the data from database
      this.setMaxPage(); // reset the max size
      this.currentPage = this.maxPage; // go to the max page
      this.option = "current";// set back to current
    }).catch(err => {
    });
},

这是其他对应的代码

getItems: function() {
  this.pages = [];
  var tempArray = [];
  tempArray = this.$store.getters.feed;
  for (var index = 0; index < tempArray.length; ++index) {
  let page = {text:tempArray[index].journal, 
  pageNumber:tempArray[index].page};
  this.pages.push(page);
 }
},

这是 store.js 中的 addJournal 函数

addJournal(context,journal) {
   console.log("this is for users", context.state.user.id)
   axios.post("/api/users/" + context.state.user.id + "/journals",journal).then(response => {
     return context.dispatch('getFeed');
        }).catch(err => {
    console.log("addJournal failed:",err);
  });
  context.dispatch('getFeed');
}

【问题讨论】:

    标签: javascript vue.js promise


    【解决方案1】:

    您需要将addJournal 转换为返回promise 的东西,以便它可以与then 一起使用:

    addJournal(context, journal) {
      console.log("this is for users", context.state.user.id)
      context.dispatch('getFeed');
      return axios.post("/api/users/" + context.state.user.id + "/journals", journal).then(response => {
        return context.dispatch('getFeed');
      }).catch(err => {
        console.log("addJournal failed:", err);
      });
    }
    

    不确定context.dispatch('getFeed'); 是做什么的,但由于posting 是异步的,所以将它移到axios.post 行上方应该没有什么问题。 axios.post 已经返回了一个 Promise,所以你只需要返回它。

    【讨论】:

    • 这个答案有效。我只想添加它以从这个 Promise 中捕获错误,在 catch 中添加 throw err
    【解决方案2】:

    .then() 承诺工作

    为了使this.$store.dispatch('addJournal').then(...) 能够按预期工作,addJournal 应该是一个承诺。

    方法如下

      addJournal(context, journal) {
        return new Promise((resolve, reject) => {
          axios
            .post("/api/users/" + context.state.user.id + "/journals", journal)
            .then(response => {
              context.dispatch("getFeed");
              resolve();
            })
            .catch(err => {
              console.log("addJournal failed:", err);
              reject(err);
            });
        });
      }
    

    【讨论】:

    • 但是axios 链已经返回了一个 Promise - 为什么还要创建另一个?
    • @CertainPerformance true。这是我个人的偏好,因为我发现在精神上更容易消费。
    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多