search

Home  >  Q&A  >  body text

javascript - asynchronous execution order in each declaration cycle in react

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

黄舟黄舟2697 days ago890

reply all(1)I'll reply

  • 漂亮男人

    漂亮男人2017-07-05 10:58:58

    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 which setTimeout 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.

    reply
    0
  • Cancelreply