promises
This commit is contained in:
parent
fabd565ebe
commit
6169650cbc
43
src/07-funktionsprogrammierung/promises.ts
Normal file
43
src/07-funktionsprogrammierung/promises.ts
Normal file
@ -0,0 +1,43 @@
|
||||
const myPromise = new Promise<number>((resolve, reject) => {
|
||||
reject('unknown error');
|
||||
setTimeout(() => {
|
||||
resolve(42);
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
// myPromise
|
||||
// .then((result) => {
|
||||
// console.log(result);
|
||||
// return result + 1;
|
||||
// })
|
||||
// .then((data) => console.log('new data: ', data))
|
||||
// .catch((error) => console.error('Fehler: ', error))
|
||||
// .finally(() => console.log('Promise abgeschlossen'));
|
||||
|
||||
async function fetchData() {
|
||||
try {
|
||||
const result = await myPromise;
|
||||
console.log('Daten empfangen: ', result);
|
||||
} catch (error) {
|
||||
console.log('Fehler: ', error);
|
||||
}
|
||||
}
|
||||
|
||||
fetchData();
|
||||
|
||||
const promise1 = new Promise((resolve) => setTimeout(() => resolve('A'), 1000));
|
||||
const promise2 = new Promise((resolve) => setTimeout(() => resolve('B'), 2000));
|
||||
|
||||
async function fetchAll() {
|
||||
const results = await Promise.all([promise1, promise2]);
|
||||
console.log(results);
|
||||
}
|
||||
|
||||
fetchAll();
|
||||
|
||||
async function fetchFirst() {
|
||||
const result = await Promise.race([promise1, promise2]);
|
||||
console.log('Fetch First: ', result);
|
||||
}
|
||||
|
||||
fetchFirst();
|
||||
Loading…
x
Reference in New Issue
Block a user