UNPKG

1.47 kBMarkdownView Raw
1# Promises
2
3Until `wpcom.js` includes full support for promises,
4there needs to be a way to offer that functionality
5without disrupting existing code. This wrapper can be
6used in new code until Promises are the native way of
7returning from async code instead of callbacks.
8
9> WARNING: If you extract a method from its parent class
10that method will lose its own `this` context and it will
11break. To ensure compliance, bind the method to its
12parent's context when sending it into the Promise
13
14```js
15let comment = wpcom.site( siteId ).comment( commentId );
16
17// Fails
18wpcom.Promise( comment.del ); // context stripped on method extraction
19
20// Succeeds
21wpcom.Promise( comment.del.bind( comment ) ); // bound context
22
23// Also succeeds
24comment = comment.del.bind( comment );
25wpcom.Promise( comment );
26```
27
28# Examples
29
30## Approving a comment
31```js
32let comment = wpcom.site( siteId ).comment( commentId );
33wpcom.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
40wpcom.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
48let post = wpcom.site( siteId ).post( postId );
49wpcom.Promise( post.get.bind( post ) )
50 .then( wpcom.Promise( post.comments.bind( post ) ) )
51 .then( renderComments );
52```