This repository was archived by the owner on May 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 279
Expand file tree
/
Copy pathgetName.js
More file actions
51 lines (41 loc) · 1.32 KB
/
getName.js
File metadata and controls
51 lines (41 loc) · 1.32 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
51
'use strict';
/*
Exercise 1: John who?
Take a look at the following function (and try it out in your console):
const getAnonName = (firstName, callback) => {
setTimeout(() => {
if (!firstName)
return callback(new Error("You didn't pass in a first name!"));
const fullName = `${firstName} Doe`;
return callback(fullName);
}, 2000);
};
getAnonName('John', console.log);
Rewrite this function, but replace the callback syntax with the Promise syntax:
Have the getAnonName function return a new Promise that uses the firstName parameter
If the Promise resolves, pass the full name as an argument to resolve with
If the Promise rejects, pass an error as the argument to reject with: "You didn't pass in a first name!"
*/
const getAnonName = firstName => {
// create a new Promise
const newPromise = new Promise((resolve, reject) => {
if (firstName) {
const fullName = `${firstName} Doe`;
resolve(`${fullName}`);
}
if (!firstName) {
reject(new Error("You didn't pass in a first name!"));
}
});
setTimeout(() => {
//call my promise and the .then() for resolved promises and catch() for rejected promises
newPromise
.then(message => {
console.log(message);
})
.catch(message => {
console.log(message);
});
}, 2000);
};
getAnonName('John');