File tree Expand file tree Collapse file tree 1 file changed +22
-8
lines changed
questions/what-are-promises-and-how-do-they-work Expand file tree Collapse file tree 1 file changed +22
-8
lines changed Original file line number Diff line number Diff line change @@ -9,18 +9,21 @@ Promises in JavaScript are objects that represent the eventual completion (or fa
99``` js
1010let promise = new Promise ((resolve , reject ) => {
1111 // asynchronous operation
12- if (/* operation successful */ ) {
12+ const success = true ;
13+ if (success) {
1314 resolve (' Success!' );
1415 } else {
1516 reject (' Error!' );
1617 }
1718});
1819
19- promise .then (result => {
20- console .log (result); // 'Success!'
21- }).catch (error => {
22- console .error (error); // 'Error!'
23- });
20+ promise
21+ .then ((result ) => {
22+ console .log (result); // 'Success!' (this will print)
23+ })
24+ .catch ((error ) => {
25+ console .error (error); // 'Error!'
26+ });
2427```
2528
2629---
@@ -46,7 +49,8 @@ You create a promise using the `Promise` constructor, which takes a function wit
4649``` js
4750let promise = new Promise ((resolve , reject ) => {
4851 // asynchronous operation
49- if (/* operation successful */ ) {
52+ const success = true ;
53+ if (success) {
5054 resolve (' Success!' );
5155 } else {
5256 reject (' Error!' );
@@ -59,12 +63,22 @@ let promise = new Promise((resolve, reject) => {
5963To handle the result of a promise, you use the ` .then() ` method for a successful outcome and the ` .catch() ` method for an error.
6064
6165``` js
66+ let promise = new Promise ((resolve , reject ) => {
67+ // asynchronous operation
68+ const success = false ;
69+ if (success) {
70+ resolve (' Success!' );
71+ } else {
72+ reject (' Error!' );
73+ }
74+ });
75+
6276promise
6377 .then ((result ) => {
6478 console .log (result); // 'Success!'
6579 })
6680 .catch ((error ) => {
67- console .error (error); // 'Error!'
81+ console .error (error); // 'Error!' (this will print)
6882 });
6983```
7084
You can’t perform that action at this time.
0 commit comments