首页 > 解决方案 > Javascript / Vue 一个接一个地执行一个函数(同步)

问题描述

我需要在 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() 似乎在我的数组完全填充之前运行.

我已经阅读了有关承诺的内容,但我不完全确定它如何适合这里。

我试图运行 this.fetchData(); 在 beforeMounted: 而不是 created: 内部,我也尝试在 axios .then() 内部调用 this.runThisAfterArrayPopulates() 但我仍然面临生产中长度为 1 的数组。

注意:我确信代码可以正常工作,它在开发中完美无缺,如果我创建这样的按钮:

<button @click="runThisAfterArrayPopulates()">Click me</button>

当我单击按钮时,行为是完美的,所以我确信它与执行顺序有关。

标签: javascriptvue.jsasynchronousvuejs2synchronization

解决方案


如下更改您的代码。

    methods: {
         fetchData() {
                
                axios.get('/api/get-data')
                    .then(res => {
                        this.myArray = res.data;
                        this.runThisAfterArrayPopulates(); // Added method call.
                    }).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 */
         }
    },


created: function () {
        // this.fetchData();
},
mounted: function () {
        this.fetchData();
},

由于处理程序方法是箭头函数,因此这不会导致问题。如果您使用普通函数代替箭头函数,请注意这个问题。

编辑: 您可以尝试移动 this.fetchData(); 调用挂载本身。


推荐阅读