Skip to content

Commit 1fe37a9

Browse files
committed
promises completed.
1 parent 3b7aaed commit 1fe37a9

File tree

2 files changed

+65
-1
lines changed

2 files changed

+65
-1
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
## Promises
2+
3+
* it is a `placeholder` (holding spot) for an `operation` that has `not` been taken place.
4+
* it's a `promise to do an action` - it hasn't done that yet! (it's `not the confirmation`! it just a promise!)
5+
* while the promise is a `placeholder for an action` which is `not completed `yet, so once it has been completed, then we can use `.then` to proceed to the following action.
6+
7+
```js
8+
var promise = this.$http.get('/some/path');
9+
promise.then(function(data){
10+
// doing something
11+
}).catch(function(err){
12+
// error handling
13+
})
14+
```
15+
16+
* note that we can also combine `.catch` with `.then` by passing it as the `second argument`:
17+
* although `.catch` is omitted but while it's located on the `second args of .then`, so it will `triggered as .catch`.
18+
19+
```js
20+
promise.then(function(data){
21+
// doing something
22+
}, function(err){
23+
// error handling
24+
});
25+
```
26+
27+
#### resolve and reject
28+
29+
* resolve and reject `are functions` that we can `trigger` them based on the `result of the promise`.
30+
* note that `without` calling `resolve()` or r`eject()`, the `.then` part won't execute!
31+
* call reject() when an `error is thrown` (we need to be `explicit` about resolve and reject!)
32+
33+
```js
34+
var timer = new Promise(function(resolve, reject) { // this function executes immediately (something like constructor!) - it's kinda bootstrap for our promise
35+
console.log('initiating Promise!!!!');
36+
setTimeout(function() {
37+
console.log('timeout done!');
38+
resolve();
39+
}, 2000);
40+
});
41+
42+
timer.then(function() { // it won't execute if we forgot to put resolve() inside the promise function (also called as Executor function)
43+
console.log('doing something else after our timeout is done....');
44+
})
45+
```
46+
47+
* a better approach to the previous example:
48+
49+
```js
50+
var timer = function(length){
51+
return new Promise(function(resolve, reject) {
52+
console.log('initiating Promise!!!!');
53+
setTimeout(function() {
54+
console.log('timeout done!');
55+
resolve();
56+
}, length);
57+
});
58+
};
59+
60+
61+
timer(3000).then(function() {
62+
console.log('doing something else after our timeout is done....');
63+
});
64+
```

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ Other useful references:
5252
05. Object additions
5353
06. Classes
5454
07. Modules
55-
08. Promises (_in progress_)
55+
08. Promises
5656
09. String additions (_in progress_)
5757
10. Array additions (_in progress_)
5858
11. Generators (_in progress_)

0 commit comments

Comments
 (0)