[英]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.