【发布时间】: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