Skip to content

Instantly share code, notes, and snippets.

@Garfonso
Created December 23, 2023 09:06
Show Gist options
  • Save Garfonso/b7e56c0cefc7edfa0a94f1c29fbeedf2 to your computer and use it in GitHub Desktop.
Save Garfonso/b7e56c0cefc7edfa0a94f1c29fbeedf2 to your computer and use it in GitHub Desktop.
Await-Spielerei
async function Berechnung () {
console.log("Berechnung: Start");
const promise = new Promise(resolve => {
setTimeout(() => { resolve(1 + 1)}, 100);
});
console.log("Berechnung: Ende");
return promise;
}
async function Unterfunktion () {
console.log("Unterfunktion: Start");
const ergebnis = Berechnung();
console.log("Unterfunktion: nach Aufruf ohne await");
console.log("Unterfunktion: Ergebnis Berechung: " + ergebnis + " - " + JSON.stringify(ergebnis));
const echtesErgebnis = await ergebnis;
console.log("Unterfunktion: Ergebnis nach await: " + echtesErgebnis);
console.log("Unterfunktion: Ende");
}
async function Hauptfunktion () {
console.log("Hauptfunktion: Start");
const promise = Unterfunktion();
console.log("Hauptfunktion: nach Aufruf ohne await"); //passiert "sofort"
await promise; //erst hier wird auf das Ergebnis gewartet.
console.log("Hauptfunktion: nach await.");
console.log("Hauptfunktion: Ende");
}
Hauptfunktion().then(() => {
console.log("Alles fertig");
}, e => {
console.log("Es gab einen Fehler: ", e);
});
@Garfonso
Copy link
Author

Ausgabe:

Hauptfunktion: Start
Unterfunktion: Start
Berechnung: Start
Berechnung: Ende
Unterfunktion: nach Aufruf ohne await
Unterfunktion: Ergebnis Berechung: [object Promise] - {}
Hauptfunktion: nach Aufruf ohne await
Unterfunktion: Ergebnis nach await: 2
Unterfunktion: Ende
Hauptfunktion: nach await.
Hauptfunktion: Ende
Alles fertig

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment