-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.js
37 lines (31 loc) · 847 Bytes
/
promise.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//basic use case
getJSON('/api/user/profile').then(displayUserProfile).catch(handleProfileError);
//Parallel Promises
Promise.all(promises)
.then(bodies => {/* do something */}
.catch(e => console.error(e));
Promise.allSettled(promises)
.then(results => {
results[0] // status fulfilled
results[1] // status rejected
results[2] // status fulfilled
});
//create a promise
function wait(duration){
return new Promise((resolve,reject) => {
if (duration < 0) {
reject(new Error('Time travel not yet implemented'));
}
setTimeout(resolve,duration);
});
}
//async await
async function getHighScore() {
let response = await fetch('/api/user/profile');
let profile = await response.json();
return profile.highScore;
}
// for/await cycle
for await (const response of promises) {
handle(response);
}