“javaScript ожидайте, пока функция закончит” Ответ

Подождите, пока функция не завершит JavaScript

function firstFunction(_callback){
    // do some asynchronous work
    // and when the asynchronous stuff is complete
    _callback();    
}

function secondFunction(){
    // call first function and pass in a callback function which
    // first function runs when it has completed
    firstFunction(function() {
        console.log('huzzah, I\'m done!');
    });    
}
Slocaly

Подождите, пока цикл закончит JavaScript

async function processArray(array) {
  // map array to promises
  const promises = array.map(delayedLog);
  // wait until all promises are resolved
  await Promise.all(promises);
  console.log('Done!');
}
Combative Cheetah

javaScript ожидайте, пока функция закончит

/*
 * 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";
MattDESTROYER

Ответы похожие на “javaScript ожидайте, пока функция закончит”

Вопросы похожие на “javaScript ожидайте, пока функция закончит”

Больше похожих ответов на “javaScript ожидайте, пока функция закончит” по JavaScript

Смотреть популярные ответы по языку

Смотреть другие языки программирования