-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise.js
97 lines (77 loc) · 2.27 KB
/
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const promise = new Promise((resolve, reject) => {
if (true) {
resolve('Stuff Worked');
} else {
reject('Error, it broke');
}
})
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'HIIII');
})
Promise.all([promise, promise2])
.then(values => {
console.log(values);
})
promise
.then(result => result + '!')
.then(result2 => {
throw Error
console.log(result2);
})
.catch(() => console.log('errrrror!'))
//////////////////
// Solve the questions below:
// #1) Create a promise that resolves in 4 seconds and returns "success" string
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success");
}, 4000)
});
// #2) Run the above promise and make it console.log "success"
promise.then(result => console.log('success'));
// #3) Read about Promise.resolve() and Promise.reject(). How can you make
// the above promise shorter with Promise.resolve() and console loggin "success"
const promiseTwo = Promise.resolve(
setTimeout(() => {
console.log("success");
}, 4000)
);
// #4) Catch this error and console log 'Ooops something went wrong'
Promise.reject('failed')
.catch(console.log("Ooops something went wrong"));
// #5) Use Promise.all to fetch all of these people from Star Wars (SWAPI) at the same time.
// Console.log the output and make sure it has a catch block as well.
const urls = [
'http://swapi.dev/api/people/1',
'http://swapi.dev/api/people/2',
'http://swapi.dev/api/people/3',
'http://swapi.dev/api/people/4'
]
Promise.all(urls.map(url =>
fetch(url).then(people => people.json())
))
.then(array => {
console.log("1", array[0])
console.log("2", array[1])
console.log("3", array[2])
console.log("4", array[3])
})
.catch(error => console.log("fuck shit went wrong", error));
// #6) Change one of your urls above to make it incorrect and fail the promise
// does your catch block handle it?
const urls = [
'http://swapi.dev/api/people/1',
'http://swapi.dev/api/people/2',
'http://swapi.dev/api/people/3',
'boom'
]
Promise.all(urls.map(url =>
fetch(url).then(people => people.json())
))
.then(array => {
console.log("1", array[0])
console.log("2", array[1])
console.log("3", array[2])
console.log("4", array[3])
})
.catch(err => console.log("fuck shit went wrong", err));