“JavaScript warten Sie, bis die Funktion fertiggestellt wird” Code-Antworten

Warten Sie, bis eine Funktion JavaScript beendet

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

Warten Sie, bis die Schleife JavaScript beendet hat

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 warten Sie, bis die Funktion fertiggestellt wird

/*
 * 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

Ähnliche Antworten wie “JavaScript warten Sie, bis die Funktion fertiggestellt wird”

Fragen ähnlich wie “JavaScript warten Sie, bis die Funktion fertiggestellt wird”

Weitere verwandte Antworten zu “JavaScript warten Sie, bis die Funktion fertiggestellt wird” auf JavaScript

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen