【发布时间】:2020-12-12 09:57:28
【问题描述】:
我需要在 VueJs 中一个接一个地运行一个函数
data: function() {
return {
stuff: '',
myArray:[
{
"id": 0,
"value1": 0,
"value2": '',
"etc": ''
},
],
};
},
methods: {
fetchData() {
axios.get('/api/get-data')
.then(res => {
this.myArray = res.data;
}).catch(err => {
console.log(err)
})
},
runThisAfterArrayPopulates(){
/*a bunch of code that relies on the contents from this.myArray , therefore I need this.myArray to be fully populated/finalized, for example*/
for (i = 0; i < this.myArray.length; i++) {
/*at this point on development server this.myArray.length is 60, on production it is 1 */
}
}
}
}
我目前执行这些功能如下:
created: function () {
this.fetchData();
},
mounted: function () {
document.onreadystatechange = () => {
if (document.readyState == "complete") {
console.log('Page completed with image and files to ensure it is executed at the very end')
this.runThisAfterArrayPopulates();
}
}
},
在我的开发本地主机上测试时,一切都按预期运行。
一旦我作为生产应用程序上传,函数 this.runThisAfterArrayPopulates();当 this.myArray 只有一个对象而不是整个 axios 数据时运行,它没有给它足够的时间来运行。我很确定发生这种情况的原因是因为在生产服务器中我的 axios 比在我的本地主机中花费的时间更长,然后我填充了数组,并且由于 Javascript 是异步的,因此函数 runThisAfterArrayPopulates() 似乎在我的数组完全填充之前运行.
我已经阅读了有关 promises 的内容,但我不完全确定它是否适合这里。
我已尝试运行 this.fetchData();在 beforeMounted: 而不是 created: 中,我也尝试在 axios .then() 中调用 this.runThisAfterArrayPopulates() 但我仍然面临生产中长度为 1 的数组。
注意:我确信代码可以正常工作,它在开发中完美无缺,如果我创建这样的按钮:
<button @click="runThisAfterArrayPopulates()">Click me</button>
当我点击按钮时行为是完美的,所以我确信它与执行顺序有关。
【问题讨论】:
-
您可以“存储” axios.get 返回的承诺...例如
this.someStoredpromise = axios.get(....etc并使用this.someStoredPromise.then(this.runThisAfterArrayPopulates)
标签: javascript vue.js asynchronous vuejs2 synchronization