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)
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();
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 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.
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;
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With