0

I noticed that the componentDidMount sometimes doesn't fire in order.

componentDidMount(){
 function1();
 function2();
 function3();
}

I noticed that function 2 sometimes inconsistently start before function 1 finished. As of right now I just put my function 2 inside function 1 at the end of the code. However, is there a better way to do this? And why its doing this?

2 Answers2

1

The code in the question will definitely call those functions in that order.

However, it sounds like those functions do asynchronous work. If so, that code will start the work of all three functions (in order) and then that work will overlap, and there's no reason the work started by function2 wouldn't complete before the work started by function1 does.

In that case, you need to provide some coordination between them if you want function2 to wait to start its process until function1 is done (and so on for function2 and function3). For instance, if they return promises, then:

function1()
.then(() => function2())
.then(() => function3())
.catch(error => {
    // ...handle/report error...
});

There I've assumed all three functions want to be called with no arguments.

If they take callbacks instead, then:

function1(() => {
    function2(() => {
        function3();
    });
});

Since callback APIs vary about how they report errors, I haven't tried to include error handling in that last example.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

You can directly use async/await for componentDidMount

In most situations, it's well enough.

async componentDidMount(){
 await function1();
 await function2();
 await function3();
}

Refer: related QA in specific: Is using async componentDidMount() good?

keikai
  • 14,085
  • 9
  • 49
  • 68
  • If you do this, you need a `try`/`catch` to handle errors, since React doesn't do anything with the promise this returns. Personally, I don't think it's best practice to return a promise from a framework lifecycle method that nothing is going to use, but it's workable with a `try`/`catch`. – T.J. Crowder Mar 21 '20 at 18:49
  • @T.J.Crowder You are right. In our practice, the only situation needs to handle errors that occur with API requests, which has been handled by common service. So it is case by case in my opinion. But I really agree with your idea. – keikai Mar 21 '20 at 18:53