componentWillMount(){
setTimeout(()=>{
alert(1);
},100)
}
componentDidMount(){
setTimeout(()=>{
alert(2);
},100)
}
The two life cycle functions in the component have asynchronous operations. The execution order is strictly in accordance with the order of the declaration cycle, that is, first 1 and then 2. It is still uncertain whether the execution order is based on the order inserted into the message queue. ? The problem can be understood as assuming that the asynchronous result of componentWillMount returns a very long time, and the asynchronous result of componentDidMount returns a very short time. Is it possible to first execute the callback result in componentDidMount, and then execute the callback result in componentWillMount
简化问题为:假设两个异步动作 A 和 B 触发顺序已知,那么 A 和 B 中同样延时的
setTimeout
是否能保证顺序?答案显然是不能的。例如当 A 和 B 之间只有微秒级延时时,两个设定了巨大延时的
setTimeout
就不能保证按照调用setTimeout
时的先后顺序触发。不能够依赖这种脆弱的时序关系来保证代码的执行顺序。在 Code Review 中如果遇到利用这种关系来实现数据初始化、异步请求等功能的代码,答主肯定是会提出意见的。对于异步的控制流,可以采用 Promise / yield 等方式来保证执行顺序,在这里就不赘述了。