示例文件
recursive_function_example_code-eyxo.vue
思路解析
核心代码
const checkReady = () => {
if (this.isThirdDataListReady) {
console.log('进行下一步');
console.log('目前表3数据拿到了this.thirdDataList', this.thirdDataList)
this.joinTableThirdToTableSecond(this.thirdDataList, this.secondDataList)
this.tableData = this.secondDataList
} else {
console.log('等了一次')
setTimeout(checkReady, 100); // 每隔 100ms 检查一次状态
}
};
checkReady(); // 启动递归检查
为何使用递归?
浏览器的内核采用单线程的运行模式,当遇到异步函数时,会让它进入等待队列。但是有的变量需要在这个异步函数完成之后进行赋值,所以改变量的赋值操作就需要等待。通过一个递归函数让他自己调用自己,每过一段时间看看这个异步函数是否完成,从而决定是否进行下一步操作。