简体   繁体   中英

Trigger function only if another function has finished in pure JavaScript?

How is it possible to trigger a function only if another function has finished?

In my actual usecase I need to trigger this three functions one after another:

dLoad();
masonry();
stylefix();

If your functions are synchronous, it is already accomplished the way you wrote it. If they're not (or some of them are not)- you can group them under one async function and await the asynchronous ones, like so:

async function func(){
  await dLoad(); // async function
  masonry(); // synchronous function
  await stylefix(); // async function
}

another possible case is that your functions are synchronous, but has some async operations inside, for example- lets say masonry() does that. what would happen in this case would be:

dLoad > masonry(without async operation) > stylefix > msonry's async operation.

It might be ok with you, as this is the definition for "the function is done" as you wrote it- it could be you do not need this async operation to complete in order to define masonry as "done" and move on to execute stylefix .

However, if you do need all async operations inside masonry to complete, you also need to make it into async function and await the async op inside that function. You won't have to await for it outside if you do not return the promise explicitely, but it will be more readable and obvious this is an async function this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM