Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

javascript wait for function to finish

/*
 * JavaScript is executed synchronously, meaning each
 * line of code is executed in the order it appears in.
 * To wait for a function to finish, simply call it...
 * Any code after it will be called after it has
 * finished.
 */
function fizzbuzz(n) {
	// (this is just the most common and easy to code version)
	if (n % 3 === 0 && n % 5 === 0) {
		return "fizzbuzz";
	} else if (n % 3 === 0) {
		return "fizz";
	} else if (n % 5 === 0) {
		return "buzz";
	}
	return n;
}

console.log(fizzbuzz(15));
console.log("This code is run after `fizzbuzz` finishes");

/*
 * The only exception to the above, is asynchronous
 * functions. An asynchronous function is not run in sync
 * with the rest of the code which is often useful. To
 * run an asynchronous function synchronously, you can
 * use the await keyword. Alternatively (and probably
 * better in most contexts) you can use the `then` and
 * `catch` methods of the promise returned by an
 * asynchronous function (or just use a promise instead
 * of an asynchronous function) to get the value returned
 * by an asynchronous function and exectute code after it
 * has run.
 */
async function fizzbuzz(n) {
	if (n % 3 === 0 && n % 5 === 0) {
		return "fizzbuzz";
	} else if (n % 3 === 0) {
		return "fizz";
	} else if (n % 5 === 0) {
		return "buzz";
	}
	throw new Error("Nice catch!");
}

fizzbuzz(15).then((res) => {
	console.log(res);
	console.log("This is run after `fizzbuzz` finishes (and so is the above `console.log`...)");
}).catch((err) => {
	console.error(err);
	console.log("This is run after `fizzbuzz` finishes (and so is the above `console.error`...)");
});






// Bonus, a more concise fizzbuzz:
const fizzbuzz = ( n ) => n % 15 ? n % 3 ? n % 5 ? n : "buzz" : "fizz" : "fizzbuzz";
 
PREVIOUS NEXT
Tagged: #javascript #wait #function #finish
ADD COMMENT
Topic
Name
9+8 =