-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComplete_a_Promise_with_resolve_reject.js
More file actions
50 lines (43 loc) · 1.46 KB
/
Complete_a_Promise_with_resolve_reject.js
File metadata and controls
50 lines (43 loc) · 1.46 KB
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
/*
Complete a Promise with resolve and reject
A promise has three states:
pending,
fulfilled and
rejected.
The promise you created in the last challenge is forever stuck
in the pending state because you did not add a way to complete
the promise.
The resolve and reject parameters given to the promise argument
are used to do this.
resolve is used when you want your promise to succeed,and
reject is used when you want it to fail.
These are methods that take an argument, as seen below.
const myPromise = new Promise((resolve, reject) => {
if(condition here) {
resolve("Promise was fulfilled");
} else {
reject("Promise was rejected");
}
});
The example above uses strings for the argument of these
functions, but it can really be anything.
Often, it might be an object, that you would use data from,
to put on your website or elsewhere.
EXERCISE
Make the promise handle success and failure.
If responseFromServer is true,
call the resolve method to successfully complete the promise
Pass resolve a string with the value 'We got the data'.
If responseFromServer is false,
use the reject method instead and pass it the string:
'Data not received'.
*/
const makeServerRequest = new Promise((resolve, reject) => {
// responseFromServer represents a response from a server
let responseFromServer;
if(responseFromServer) {
resolve('We got the data');
} else {
reject('Data not received');
}
});