Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a function call to wait till another one is finished

Tags:

So what I want is,

functionA(); // this completes 
functionB(); // then this runs

Im trying to seed multiple collections into a database in one go, and when I've procedurally put each collection after each other only the last one is seeded into the database. I'm trying to figure-out how to keep Javascript from being Asynchronous, so I can have each step wait till the previous one is done. I feel like I could use Underscores "defer" method, which Defers invoking the function until the current call stack has cleared; I just don't know how to use it.

I"m using underscores delay method, and that works but its dependent on the seed sizes and I want to get away from that.

The code looks like this:

// creates and sends seed data to a collecion("blah") inside a db("heroes")
var blog = MeanSeed.init("heroes", "blah");
blog.exportToDB();

// this waits a second till it starts seeding the "heroes" DB with its "aliens" collection
_.delay(function() {
  var user = MeanSeed.init("heroes", "aliens");   
  user.exportToDB();  
}, 1000)
like image 292
Mitch Kroska Avatar asked May 23 '16 19:05

Mitch Kroska


People also ask

How do you make a function wait for another function to finish?

Wait for function to finish using async/await keywords As you already know from the Promise explanation above, you need to chain the call to the function that returns a Promise using then/catch functions. The await keyword allows you to wait until the Promise object is resolved or rejected: await first(); second();

How do you make a function wait for a second?

To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.

How do you wait for setTimeout to finish?

How to Wait for a Function to Finish in JavaScript. Using a Callback Function With setTimeout() to Wait for a Function to Finish. Using await Keyword and setTimeout() to Wait for a Function to Finish.


2 Answers

I can recommend using Promises. It's pretty new and it was introduced in ES6 (but it's already in Node 5-6). An example for usage:

new Promise(function(resolve, reject){
    // do something in A
    resolve();
}).then(function(result) {
    // do something else in B
    return result;
})
like image 75
András Avatar answered Oct 13 '22 00:10

András


You can use a callback function, like this:

function functionA(done){
    //do some stuff
    done(true);
}
function functionB(){

}

functionA(function(success){
    if(success)
        functionB();
});

Or, you can use promises.

like image 24
JstnPwll Avatar answered Oct 13 '22 01:10

JstnPwll