1 | # Promises
|
2 |
|
3 | Until `wpcom.js` includes full support for promises,
|
4 | there needs to be a way to offer that functionality
|
5 | without disrupting existing code. This wrapper can be
|
6 | used in new code until Promises are the native way of
|
7 | returning from async code instead of callbacks.
|
8 |
|
9 | > WARNING: If you extract a method from its parent class
|
10 | that method will lose its own `this` context and it will
|
11 | break. To ensure compliance, bind the method to its
|
12 | parent's context when sending it into the Promise
|
13 |
|
14 | ```js
|
15 | let comment = wpcom.site( siteId ).comment( commentId );
|
16 |
|
17 | // Fails
|
18 | wpcom.Promise( comment.del ); // context stripped on method extraction
|
19 |
|
20 | // Succeeds
|
21 | wpcom.Promise( comment.del.bind( comment ) ); // bound context
|
22 |
|
23 | // Also succeeds
|
24 | comment = comment.del.bind( comment );
|
25 | wpcom.Promise( comment );
|
26 | ```
|
27 |
|
28 | # Examples
|
29 |
|
30 | ## Approving a comment
|
31 | ```js
|
32 | let comment = wpcom.site( siteId ).comment( commentId );
|
33 | wpcom.Promise( comment.update.bind( comment ), { status: 'approved' } )
|
34 | .then( response => updateComment( commentId, response ) )
|
35 | .catch( error => alert( error ) );
|
36 | ```
|
37 |
|
38 | ## Requesting the freshly-pressed list
|
39 | ```js
|
40 | wpcom.Promise( wpcom.freshlyPressed.bind( wpcom ) )
|
41 | .timeout( 4000 ) // give up if longer than 4s
|
42 | .then( handleData )
|
43 | .catch( notifyNetworkError );
|
44 | ```
|
45 |
|
46 | ## Chaining promises
|
47 | ```js
|
48 | let post = wpcom.site( siteId ).post( postId );
|
49 | wpcom.Promise( post.get.bind( post ) )
|
50 | .then( wpcom.Promise( post.comments.bind( post ) ) )
|
51 | .then( renderComments );
|
52 | ```
|