[英]Promise Chain Out of Order
我最近在javascript中,特别是在Vue.js中遇到了Promise Chain问题。 这是我的代码,我有一个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');
}
您需要将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');
可以,但是由于post
是异步的,因此将其axios.post
行上方应该没有任何问题。 axios.post
已经返回了一个承诺,因此您只需要返回它即可。
.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);
});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.