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
The simplified question is: Assuming that the triggering order of two asynchronous actions A and B is known, can the
setTimeout
with the same delay in A and B guarantee the order?The answer is obviously no. For example, when there is only a microsecond delay between A and B, two
setTimeout
with huge delays cannot be guaranteed to be triggered in the order in whichsetTimeout
is called.You cannot rely on this fragile timing relationship to ensure the execution order of the code. In Code Review, if you encounter code that uses this relationship to implement functions such as data initialization and asynchronous requests, the respondent will definitely give his opinion. For asynchronous control flow, Promise / yield and other methods can be used to ensure the execution order, which will not be described here.