|
525
|
1 |
<!DOCTYPE html> |
|
|
2 |
<html lang="en"> |
|
|
3 |
<head> |
|
|
4 |
<meta charset="utf-8"> |
|
|
5 |
<title>Promise</title> |
|
|
6 |
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,700,400italic,700italic"> |
|
|
7 |
<link rel="stylesheet" href="../../build/cssgrids/cssgrids-min.css"> |
|
|
8 |
<link rel="stylesheet" href="../assets/css/main.css"> |
|
|
9 |
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css"> |
|
|
10 |
<link rel="shortcut icon" type="image/png" href="../assets/favicon.png"> |
|
|
11 |
<script src="../../build/yui/yui-min.js"></script> |
|
|
12 |
|
|
|
13 |
</head> |
|
|
14 |
<body> |
|
|
15 |
<!-- |
|
|
16 |
<a href="https://github.com/yui/yui3"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub"></a> |
|
|
17 |
--> |
|
|
18 |
<div id="doc"> |
|
|
19 |
<div id="hd"> |
|
|
20 |
<h1><img src="http://yuilibrary.com/img/yui-logo.png"></h1> |
|
|
21 |
</div> |
|
|
22 |
|
|
|
23 |
<a href="#toc" class="jump">Jump to Table of Contents</a> |
|
|
24 |
|
|
|
25 |
|
|
|
26 |
<h1>Promise</h1> |
|
|
27 |
<div class="yui3-g"> |
|
|
28 |
<div class="yui3-u-3-4"> |
|
|
29 |
<div id="main"> |
|
|
30 |
<div class="content"><link type="text/css" rel="stylesheet" href="../../build/cssbutton/cssbutton-min.css"> |
|
|
31 |
<div class="intro"> |
|
|
32 |
<p> |
|
|
33 |
Promises are a tool to help write asynchronous code in a more readable |
|
|
34 |
style that looks more like synchronous code. |
|
|
35 |
</p> |
|
|
36 |
|
|
|
37 |
<p> |
|
|
38 |
In short, promises allow you to interact with a value that may or may |
|
|
39 |
not be available yet. |
|
|
40 |
</p> |
|
|
41 |
|
|
|
42 |
<p> |
|
|
43 |
Promises let wrap, and even chain, asynchronous operations using a |
|
|
44 |
consistent API, avoiding writing nested anonymous callbacks (the |
|
|
45 |
"pyramid of doom"). And they let you handle any errors that happen |
|
|
46 |
during those operations. |
|
|
47 |
</p> |
|
|
48 |
|
|
|
49 |
<p> |
|
|
50 |
The <code>Y.Promise</code> class is compatible with the |
|
|
51 |
<a href="http://promises-aplus.github.com/promises-spec/">Promises/A+</a> |
|
|
52 |
specification. |
|
|
53 |
</p> |
|
|
54 |
|
|
|
55 |
</div> |
|
|
56 |
|
|
|
57 |
<h2 id="getting-started">Getting Started</h2> |
|
|
58 |
|
|
|
59 |
<p> |
|
|
60 |
To include the source files for Promise and its dependencies, first load |
|
|
61 |
the YUI seed file if you haven't already loaded it. |
|
|
62 |
</p> |
|
|
63 |
|
|
|
64 |
<pre class="code prettyprint"><script src="http://yui.yahooapis.com/3.10.3/build/yui/yui-min.js"></script></pre> |
|
|
65 |
|
|
|
66 |
|
|
|
67 |
<p> |
|
|
68 |
Next, create a new YUI instance for your application and populate it with the |
|
|
69 |
modules you need by specifying them as arguments to the <code>YUI().use()</code> method. |
|
|
70 |
YUI will automatically load any dependencies required by the modules you |
|
|
71 |
specify. |
|
|
72 |
</p> |
|
|
73 |
|
|
|
74 |
<pre class="code prettyprint"><script> |
|
|
75 |
// Create a new YUI instance and populate it with the required modules. |
|
|
76 |
YUI().use('promise', function (Y) { |
|
|
77 |
// Promise is available and ready for use. Add implementation |
|
|
78 |
// code here. |
|
|
79 |
}); |
|
|
80 |
</script></pre> |
|
|
81 |
|
|
|
82 |
|
|
|
83 |
<p> |
|
|
84 |
For more information on creating YUI instances and on the |
|
|
85 |
<a href="http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_use"><code>use()</code> method</a>, see the |
|
|
86 |
documentation for the <a href="../yui/index.html">YUI Global Object</a>. |
|
|
87 |
</p> |
|
|
88 |
|
|
|
89 |
|
|
|
90 |
<h2 id="the-basics">The Basics</h2> |
|
|
91 |
|
|
|
92 |
<p> |
|
|
93 |
As mentioned above, promises allow you to interact with a value that may or |
|
|
94 |
may not be available yet. In synchronous code, values are assigned to |
|
|
95 |
variables and immediately available to use, but if you need to use or |
|
|
96 |
assign a value that depends on an asynchronous operation to get, the |
|
|
97 |
rest of your code needs to be wrapped in a callback that is executed when |
|
|
98 |
that asynchronous operations completes. |
|
|
99 |
</p> |
|
|
100 |
|
|
|
101 |
<p> |
|
|
102 |
Callbacks work, but they don't maintain any state, the APIs responsible for |
|
|
103 |
the callbacks are likely to differ, and they might not handle errors. It's |
|
|
104 |
also quite easy to find yourself building up multi-step transactions by |
|
|
105 |
nesting anonymous callbacks multiple levels deep. |
|
|
106 |
</p> |
|
|
107 |
|
|
|
108 |
<p> |
|
|
109 |
Promises address this by providing an object that can be referred to |
|
|
110 |
immediately and any time in the future that represents the value produced |
|
|
111 |
by the asynchronous operation. Here's how you use them: |
|
|
112 |
</p> |
|
|
113 |
|
|
|
114 |
<h3 id="two-simple-methods">Two Simple Methods</h3> |
|
|
115 |
|
|
|
116 |
<p> |
|
|
117 |
Promises operate using two methods: the <code>Y.Promise</code> constructor, and the |
|
|
118 |
promise instance's <code>then()</code> method. |
|
|
119 |
</p> |
|
|
120 |
|
|
|
121 |
<pre class="code prettyprint">// Create a promise for a value |
|
|
122 |
var promise = new Y.Promise(function (resolve, reject) { |
|
|
123 |
var promisedValue; |
|
|
124 |
|
|
|
125 |
// ...do some work to assign promisedValue, most likely asynchronously |
|
|
126 |
|
|
|
127 |
// When the work is done, fulfill the promise with the resolve function, |
|
|
128 |
// which was passed in the arguments. |
|
|
129 |
resolve(promisedValue); |
|
|
130 |
|
|
|
131 |
// Or if something went wrong, reject the promise with the reject function, |
|
|
132 |
// also passed in the arguments. |
|
|
133 |
reject(reasonForFailure); |
|
|
134 |
}); |
|
|
135 |
|
|
|
136 |
// Do something with the promised value using the then() method. then() takes |
|
|
137 |
// two functions as arguments. promise.then(onFulfilled, onRejected); |
|
|
138 |
promise.then( |
|
|
139 |
// aka onFulfilled |
|
|
140 |
function (promisedValue) { |
|
|
141 |
alert("Here's that value I promised I'd get for you: " + promisedValue); |
|
|
142 |
}, |
|
|
143 |
|
|
|
144 |
// aka onRejected |
|
|
145 |
function (reason) { |
|
|
146 |
alert("Oh no! I broke my promise. Here's why: " + reason); |
|
|
147 |
});</pre> |
|
|
148 |
|
|
|
149 |
|
|
|
150 |
<h3 id="creating-a-promise">Creating a Promise</h3> |
|
|
151 |
|
|
|
152 |
<p> |
|
|
153 |
The <code>Y.Promise</code> constructor takes as its argument a function we'll call the |
|
|
154 |
"executor function". This function is responsible for saying when the |
|
|
155 |
promised value is ready, or notifying that something went wrong. |
|
|
156 |
</p> |
|
|
157 |
|
|
|
158 |
<p> |
|
|
159 |
The executor function receives two customized functions as its arguments, |
|
|
160 |
commonly called <code>resolve</code> and <code>reject</code>. If the work in the executor |
|
|
161 |
function to get the promised value completes successfully, pass the value |
|
|
162 |
to the <code>resolve()</code> method. If something went wrong, pass the |
|
|
163 |
reason—commonly an <code>Error</code>—to the <code>reject()</code> method. |
|
|
164 |
</p> |
|
|
165 |
|
|
|
166 |
<pre class="code prettyprint">// dataPromise represents the data parsed from the IO response, |
|
|
167 |
// or the error that occurred fetching it |
|
|
168 |
var dataPromise = new Y.Promise(function (resolve, reject) { |
|
|
169 |
Y.io('getdata.php', { |
|
|
170 |
on: { |
|
|
171 |
success: function (id, response) { |
|
|
172 |
// The IO completed, so the promise can be resolved |
|
|
173 |
try { |
|
|
174 |
resolve(Y.JSON.parse(response.responseText)); |
|
|
175 |
} catch (e) { |
|
|
176 |
// any failure to produce the value is a rejection |
|
|
177 |
reject(e); |
|
|
178 |
} |
|
|
179 |
}, |
|
|
180 |
failure: function (id, response) { |
|
|
181 |
// The IO failed |
|
|
182 |
reject(new Error("getdata.php request failed: " + response)); |
|
|
183 |
} |
|
|
184 |
} |
|
|
185 |
}); |
|
|
186 |
});</pre> |
|
|
187 |
|
|
|
188 |
|
|
|
189 |
<h3 id="resolving-a-promise">Resolving a Promise</h3> |
|
|
190 |
|
|
|
191 |
<p> |
|
|
192 |
Promises can be in one of three states: |
|
|
193 |
</p> |
|
|
194 |
|
|
|
195 |
<ol> |
|
|
196 |
<li><code>pending</code> - the promised value is not ready yet (default)</li> |
|
|
197 |
<li><code>fulfilled</code> - the value is ready</li> |
|
|
198 |
<li><code>rejected</code> - something went wrong, the value can't be produced</li> |
|
|
199 |
</ol> |
|
|
200 |
|
|
|
201 |
<p> |
|
|
202 |
"Resolving" a promise moves a <code>pending</code> promise to either <code>fulfilled</code> or |
|
|
203 |
<code>rejected</code>, though the term is often used interchangeably with "fulfill" |
|
|
204 |
(it's good to have a positive outlook). Once a promise is fulfilled or |
|
|
205 |
rejected, it can't be transitioned to another state. |
|
|
206 |
</p> |
|
|
207 |
|
|
|
208 |
<p> |
|
|
209 |
There are two ways promises get resolved. The first is using the |
|
|
210 |
<code>resolve()</code> function passed to the executor function in the <code>Y.Promise</code> |
|
|
211 |
constructor. We'll talk about the second way when we discuss <a |
|
|
212 |
href="#promise-chaining">promise chaining</a>. |
|
|
213 |
</p> |
|
|
214 |
|
|
|
215 |
<h3 id="getting-the-promised-value">Getting the Promised Value</h3> |
|
|
216 |
|
|
|
217 |
<p> |
|
|
218 |
Since the promised value probably isn't ready when you create the promise, |
|
|
219 |
you can't synchronously consume the value. Schedule the code that will use |
|
|
220 |
the promised value to execute with the promise's <code>then()</code> method. |
|
|
221 |
</p> |
|
|
222 |
|
|
|
223 |
<p> |
|
|
224 |
<code>then()</code> takes two callbacks as arguments, that we call <code>onFulfilled</code> and |
|
|
225 |
<code>onRejected</code>. As you might have guessed, the <code>onFulfilled</code> callback is |
|
|
226 |
executed if the promise resolves to a value, and the <code>onRejected</code> callback |
|
|
227 |
is executed if it is rejected. |
|
|
228 |
</p> |
|
|
229 |
|
|
|
230 |
<p> |
|
|
231 |
Only one of the callbacks will be executed, and only once. |
|
|
232 |
<a href="#omitting-onfulfilled-or-onrejected">Both callbacks are |
|
|
233 |
optional</a>, though in practice you'll always pass at least one to |
|
|
234 |
<code>then()</code>. |
|
|
235 |
</p> |
|
|
236 |
|
|
|
237 |
<pre class="code prettyprint">var stuff; |
|
|
238 |
|
|
|
239 |
var promise = new Y.Promise(getStuff); |
|
|
240 |
|
|
|
241 |
// When getStuff says the promise is fulfilled, update the stuff variable. |
|
|
242 |
// No onRejected callback is passed, so if there was an error, do nothing. |
|
|
243 |
promise.then(function (stuffValue) { |
|
|
244 |
stuff = stuffValue; |
|
|
245 |
}); |
|
|
246 |
|
|
|
247 |
// Stuff isn't populated yet because the promise hasn't been fulfilled |
|
|
248 |
console.log("Stuff value is " + stuff); // => "Stuff value is undefined"</pre> |
|
|
249 |
|
|
|
250 |
|
|
|
251 |
<p> |
|
|
252 |
You can call <code>then()</code> on the promise as many times as you like. The same |
|
|
253 |
value will be passed to each <code>then()</code> callback. |
|
|
254 |
</p> |
|
|
255 |
|
|
|
256 |
<h4 id="always-asynchronous">Always Asynchronous</h4> |
|
|
257 |
|
|
|
258 |
<p> |
|
|
259 |
It's important to note that even if the <code>getStuff</code> function above resolved |
|
|
260 |
the promise immediately, callbacks scheduled with <code>then</code> will |
|
|
261 |
<strong>always be called asynchronously</strong>. So the example code above |
|
|
262 |
will always log "Stuff value is undefined", regardless of whether |
|
|
263 |
<code>getStuff</code> operates synchronously or asynchronously. |
|
|
264 |
</p> |
|
|
265 |
|
|
|
266 |
<p> |
|
|
267 |
To limit the runtime impact of <code>then</code> callbacks always being executed |
|
|
268 |
asynchronously, they are scheduled using |
|
|
269 |
<a href="http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_soon"><code>Y.soon()</code></a>, which |
|
|
270 |
will attempt to avoid any minimum delay that some browsers impose on |
|
|
271 |
<code>setTimeout</code>. |
|
|
272 |
</p> |
|
|
273 |
|
|
|
274 |
<h2 id="the-not-so-basics">The Not-so Basics</h2> |
|
|
275 |
|
|
|
276 |
<h3 id="promise-chaining">Promise Chaining</h3> |
|
|
277 |
|
|
|
278 |
<p> |
|
|
279 |
Here's where things start getting fun. When you call <code>promise.then(...)</code>, |
|
|
280 |
a new promise is returned. The new promise will resolve when either of the |
|
|
281 |
original promise's <code>onFulfilled</code> or <code>onRejected</code> functions returns a value |
|
|
282 |
or throws an error. This allows you to schedule several operations using |
|
|
283 |
chained <code>then()</code> calls. |
|
|
284 |
</p> |
|
|
285 |
|
|
|
286 |
<pre class="code prettyprint">// Verbose form |
|
|
287 |
startSpinner(); |
|
|
288 |
|
|
|
289 |
// Create the initial promise |
|
|
290 |
var userDataLoaded = new Y.Promise(function (resolve, reject) { |
|
|
291 |
Y.io('getUserData.php', { |
|
|
292 |
data: 'id=1234', |
|
|
293 |
on: { |
|
|
294 |
success: function (id, response) { |
|
|
295 |
try { |
|
|
296 |
resolve(Y.JSON.parse(response.responseText)); |
|
|
297 |
} catch (e) { |
|
|
298 |
reject(e); |
|
|
299 |
} |
|
|
300 |
}, |
|
|
301 |
failure: function (id, response) { |
|
|
302 |
reject(new Error(response)); |
|
|
303 |
} |
|
|
304 |
} |
|
|
305 |
}); |
|
|
306 |
}); |
|
|
307 |
|
|
|
308 |
// after the user data is loaded, render stuff or show the loading error |
|
|
309 |
var uiUpdated = userDataLoaded.then(renderTemplates, showError); |
|
|
310 |
|
|
|
311 |
// after the UI is updated, stop the spinner |
|
|
312 |
uiUpdated.then(stopSpinner); |
|
|
313 |
|
|
|
314 |
// Concise form (more common) |
|
|
315 |
// Note Y.Promise can be called without 'new' |
|
|
316 |
Y.Promise(function (resolve, reject) { Y.io(...); }) |
|
|
317 |
.then(renderTemplates, showError) // returns another promise |
|
|
318 |
.then(stopSpinner); // returns another promise</pre> |
|
|
319 |
|
|
|
320 |
|
|
|
321 |
<p> |
|
|
322 |
A chained promise is resolved by the return value of the previous promise's |
|
|
323 |
callbacks. Or, if an error is thrown, the chained promise is rejected. |
|
|
324 |
</p> |
|
|
325 |
|
|
|
326 |
<p> |
|
|
327 |
Note that functions will return <code>undefined</code> if no explicit <code>return</code> |
|
|
328 |
statement is included. That will result in the promise being fulfilled with |
|
|
329 |
a value of <code>undefined</code>. Sometimes that's okay, but it's often helpful to pass |
|
|
330 |
along <em>some</em> data. |
|
|
331 |
</p> |
|
|
332 |
|
|
|
333 |
<pre class="code prettyprint">function renderTemplates(userData) { |
|
|
334 |
// Update the UI |
|
|
335 |
Y.one('#userForm').setHTML(Y.Lang.sub(MyApp.userFormTemplate, userData)); |
|
|
336 |
|
|
|
337 |
// return a value to resolve the chained promise (aka uiUpdated) and pass |
|
|
338 |
// to the uiUpdated's then(onFulfilled) callback, stopSpinner |
|
|
339 |
return true; |
|
|
340 |
} |
|
|
341 |
|
|
|
342 |
function stopSpinner(updated) { |
|
|
343 |
// updated will receive the return value of the previous promise's callback |
|
|
344 |
// In this case, the boolean true. |
|
|
345 |
var face = updated ? happyFace : sadFace; |
|
|
346 |
|
|
|
347 |
spinnerNode.replace(face).hide(true); |
|
|
348 |
} |
|
|
349 |
|
|
|
350 |
// Using the original promise from the example above |
|
|
351 |
userDataLoaded |
|
|
352 |
.then(renderTemplates, showError) |
|
|
353 |
.then(stopSpinner);</pre> |
|
|
354 |
|
|
|
355 |
|
|
|
356 |
<h3 id="handling-errors">Handling Errors</h3> |
|
|
357 |
|
|
|
358 |
<p> |
|
|
359 |
When a promise is rejected, the <code>onRejected</code> callback (the second argument |
|
|
360 |
to <code>then()</code>) is executed. Like <code>onFulfilled</code>, it is called with whatever is |
|
|
361 |
passed to the executor function's <code>reject()</code> function. |
|
|
362 |
</p> |
|
|
363 |
|
|
|
364 |
<p> |
|
|
365 |
The <code>onRejected</code> callback can then re-throw the error to propagate the |
|
|
366 |
failed state, or recover from the failure by returning a value. Again, |
|
|
367 |
without an explicit <code>throw</code> or <code>return</code>, the callback will return |
|
|
368 |
<code>undefined</code> <em>which will mark the failure as recovered</em>, but with a resolved |
|
|
369 |
value of <code>undefined</code>. This may not be what you want! |
|
|
370 |
</p> |
|
|
371 |
|
|
|
372 |
<pre class="code prettyprint">function showError(reason) { |
|
|
373 |
Y.one('#userForm').hide(true); |
|
|
374 |
|
|
|
375 |
Y.one('#message .details').setHTML(reason.message || reason); |
|
|
376 |
Y.one('#message').show(); |
|
|
377 |
|
|
|
378 |
// Choosing not to re-throw the error, but consider it recovered from for |
|
|
379 |
// the sake of this transaction. Returning false as resolved value to send |
|
|
380 |
// to stopSpinner. |
|
|
381 |
return false; |
|
|
382 |
} |
|
|
383 |
|
|
|
384 |
userDataLoaded |
|
|
385 |
.then(renderTemplates, showError) |
|
|
386 |
.then(stopSpinner);</pre> |
|
|
387 |
|
|
|
388 |
|
|
|
389 |
<p> |
|
|
390 |
Because <code>showError</code> returned a value, and didn't re-throw the <code>reason</code>, |
|
|
391 |
the promise wrapping <code>renderTemplates</code> and <code>showError</code> was resolved to a |
|
|
392 |
"fulfilled" state with a value of <code>false</code>. Since the promise was fulfilled, |
|
|
393 |
not rejected, that promise's <code>onFulfilled</code> callback (<code>stopSpinner</code>) is |
|
|
394 |
called with the value <code>false</code>. |
|
|
395 |
</p> |
|
|
396 |
|
|
|
397 |
<h4 id="caveat-the-unhandled-rejection">Caveat: The Unhandled Rejection</h4> |
|
|
398 |
|
|
|
399 |
<p> |
|
|
400 |
Because thrown errors are caught by the <code>Y.Promise</code> internals and used as |
|
|
401 |
a signal to reject a promise, it's possible to write promise chains that |
|
|
402 |
fail silently. This can be hard to debug. |
|
|
403 |
</p> |
|
|
404 |
|
|
|
405 |
<p> |
|
|
406 |
To avoid this, it's highly recommended to <strong>always</strong> include |
|
|
407 |
an <code>onRejected</code> callback at the end of your promise chains. The reason you |
|
|
408 |
only need to put one at the end is discussed below. |
|
|
409 |
</p> |
|
|
410 |
|
|
|
411 |
<h3 id="omitting-onfulfilled-or-onrejected">Omitting <code>onFulfilled</code> or <code>onRejected</code></h3> |
|
|
412 |
|
|
|
413 |
<p> |
|
|
414 |
Both <code>onFulfilled</code> and <code>onRejected</code> callbacks are optional, though in |
|
|
415 |
practice, you will always pass at least one. When a callback isn't provided |
|
|
416 |
for a <code>then()</code> call in a promise chain, that promise is automatically |
|
|
417 |
fulfilled with the value returned from the prior <code>onFulfilled</code> callback or |
|
|
418 |
rejected with the reason thrown from the prior <code>onRejected</code> callback. |
|
|
419 |
</p> |
|
|
420 |
|
|
|
421 |
<pre class="code prettyprint">getHandleFromServerA() |
|
|
422 |
.then(null, getHandleFromServerB) |
|
|
423 |
.then(getUserData) |
|
|
424 |
.then(renderTemplates, showError); |
|
|
425 |
|
|
|
426 |
// Same code, commented |
|
|
427 |
// Try to get a DB handle from Server A... |
|
|
428 |
getHandleFromServerA() |
|
|
429 |
// if that fails, try Server B, otherwise, pass through the Server A handle |
|
|
430 |
.then(null, getHandleFromServerB) |
|
|
431 |
// if either server provided a handle, get user data. |
|
|
432 |
// otherwise, there was an error, so pass it along the chain |
|
|
433 |
.then(getUserData) |
|
|
434 |
// render the user data if everything worked. |
|
|
435 |
// if there was an error getting a DB handle or getting user data show it |
|
|
436 |
.then(renderTemplates, showError);</pre> |
|
|
437 |
|
|
|
438 |
|
|
|
439 |
<p> |
|
|
440 |
It's not uncommon to see promise chains with only <code>onFulfilled</code> callbacks, |
|
|
441 |
then an <code>onRejected</code> callback at the very end. |
|
|
442 |
</p> |
|
|
443 |
|
|
|
444 |
<h3 id="chaining-asynchronous-operations">Chaining Asynchronous Operations</h3> |
|
|
445 |
|
|
|
446 |
<p> |
|
|
447 |
As mentioned above, the return value from either <code>onFulfilled</code> or |
|
|
448 |
<code>onRejected</code> fulfills the promise with that value. <em>There is one |
|
|
449 |
exception</em>. |
|
|
450 |
</p> |
|
|
451 |
|
|
|
452 |
<p> |
|
|
453 |
If you return a promise instead of a regular value (call it |
|
|
454 |
<code>returnedPromise</code>), the original promise will wait for <code>returnedPromise</code> to |
|
|
455 |
resolve, and adopt its state when it does. So if <code>returnedPromise</code> is |
|
|
456 |
fulfilled, the original promise is fulfilled with the same value, and if |
|
|
457 |
<code>returnedPromise</code> is rejected, the original promise is rejected with the |
|
|
458 |
same reason. |
|
|
459 |
</p> |
|
|
460 |
|
|
|
461 |
<pre class="code prettyprint">Y.Promise(function (resolve, reject) { |
|
|
462 |
Y.io('getDataUrl.php', { |
|
|
463 |
on: { |
|
|
464 |
success: function (id, response) { |
|
|
465 |
resolve(response.responseText); |
|
|
466 |
}, |
|
|
467 |
failure: function () { |
|
|
468 |
reject(new Error("Can't reach the server")); |
|
|
469 |
} |
|
|
470 |
} |
|
|
471 |
}); |
|
|
472 |
}) |
|
|
473 |
// Chain another async operation by returning a promise. |
|
|
474 |
// Don't worry, we'll wait for you. |
|
|
475 |
.then(function (data) { |
|
|
476 |
return new Y.Promise(function (resolve, reject) { |
|
|
477 |
// Do another async operation |
|
|
478 |
Y.jsonp(data.url, { |
|
|
479 |
on: { |
|
|
480 |
success: resolve, |
|
|
481 |
failure: reject |
|
|
482 |
} |
|
|
483 |
}); |
|
|
484 |
}); |
|
|
485 |
}) |
|
|
486 |
// Called after both async operations have completed. The data response |
|
|
487 |
// from the JSONP call is passed to renderTemplates |
|
|
488 |
.then(renderTemplates) |
|
|
489 |
// Then wait for 2 seconds before continuing the chain |
|
|
490 |
.then(function () { |
|
|
491 |
return new Y.Promise(function (resolve) { |
|
|
492 |
setTimeout(resolve, 2000); |
|
|
493 |
}); |
|
|
494 |
}) |
|
|
495 |
.then(hideMessage, showError);</pre> |
|
|
496 |
|
|
|
497 |
|
|
|
498 |
<p> |
|
|
499 |
Similarly, you can pass a promise to the <code>resolve()</code> function passed to the |
|
|
500 |
<code>Y.Promise</code> executor function. |
|
|
501 |
</p> |
|
|
502 |
|
|
|
503 |
<p> |
|
|
504 |
<strong>Caution</strong>: Do not pass a promise to <code>reject()</code> or <code>throw</code> a |
|
|
505 |
promise from a callback. You're definitely doing something wrong if you |
|
|
506 |
find yourself doing that. |
|
|
507 |
</p> |
|
|
508 |
|
|
|
509 |
<h3 id="ywhen-for-promise-wrapping"><code>Y.when()</code> For Promise Wrapping</h3> |
|
|
510 |
|
|
|
511 |
<p> |
|
|
512 |
If you're unsure if a variable has a value or a promise, or you want an API |
|
|
513 |
to support both value or promise inputs, use <code>Y.when(value)</code> to wrap |
|
|
514 |
non-promise values in promises. Wrapped non-promise values will be |
|
|
515 |
immediately fulfilled with the wrapped value. Passing a promise to <code>Y.when</code> |
|
|
516 |
will return the promise. |
|
|
517 |
</p> |
|
|
518 |
|
|
|
519 |
<pre class="code prettyprint">// Accept either a regular object or a promise to save |
|
|
520 |
MyDatabase.prototype.save = function (key, data) { |
|
|
521 |
// Ensure we are dealing with a promise and call then() to get its value |
|
|
522 |
// return the promise chained off this then() call |
|
|
523 |
return Y.when(data).then(function (data) { |
|
|
524 |
// Store the data somehow, for instance in localStorage |
|
|
525 |
localStorage.set(key, data); |
|
|
526 |
}); |
|
|
527 |
};</pre> |
|
|
528 |
|
|
|
529 |
|
|
|
530 |
<h3 id="non-serial-operation-batching">Non-serial Operation Batching</h3> |
|
|
531 |
|
|
|
532 |
<p> |
|
|
533 |
Promise chaining works great to serialize synchronous and asynchronous |
|
|
534 |
operations, but often several asynchronous operations can be performed |
|
|
535 |
simultaneously. This is where <code>Y.batch()</code> comes in. |
|
|
536 |
</p> |
|
|
537 |
|
|
|
538 |
<p> |
|
|
539 |
<code>Y.batch()</code> takes any number of promises as arguments, and returns a new |
|
|
540 |
promise that will resolve when all the batched promises have resolved. The |
|
|
541 |
resolved value will be an array of values from the individual promises, in |
|
|
542 |
the order they were passed to <code>Y.batch()</code>. |
|
|
543 |
</p> |
|
|
544 |
|
|
|
545 |
<p> |
|
|
546 |
If any one of the batched promises should be rejected, the batch promise |
|
|
547 |
is immediately rejected with that reason, so failures can be dealt with |
|
|
548 |
sooner rather than later. |
|
|
549 |
</p> |
|
|
550 |
|
|
|
551 |
<pre class="code prettyprint">Y.batch( |
|
|
552 |
getUserAccountInfo(userId), |
|
|
553 |
getUserPosts(userId, { page: 1, postsPerPage: 5 }), |
|
|
554 |
getUserRank(userId) |
|
|
555 |
) |
|
|
556 |
.then(function (data) { |
|
|
557 |
var account = data[0], |
|
|
558 |
posts = data[1], |
|
|
559 |
rank = data[2]; |
|
|
560 |
|
|
|
561 |
... |
|
|
562 |
}, handleError);</pre> |
|
|
563 |
|
|
|
564 |
|
|
|
565 |
<!--h3>Custom Promises</h3> |
|
|
566 |
|
|
|
567 |
<p> |
|
|
568 |
`Y.Promise is built to support creating custom subclasses that support |
|
|
569 |
more descriptive names. Subclass methods can access the resolution |
|
|
570 |
mechanism for the promise via <code>this._resolver</code>. |
|
|
571 |
</p> |
|
|
572 |
|
|
|
573 |
|
|
|
574 |
<pre class="code prettyprint"></pre> |
|
|
575 |
|
|
|
576 |
--> |
|
|
577 |
|
|
|
578 |
<h2 id="faq">FAQ</h2> |
|
|
579 |
|
|
|
580 |
<ul> |
|
|
581 |
<li> |
|
|
582 |
<a href="#diff">What's the difference between <code>Y.Promise</code> and...?</a> |
|
|
583 |
</li> |
|
|
584 |
<li> |
|
|
585 |
<a href="#plans">What are the plans for promises in the library?</a> |
|
|
586 |
</li> |
|
|
587 |
</ul> |
|
|
588 |
|
|
|
589 |
<h3 id="diff">What's the difference between <code>Y.Promise</code> and...</h3> |
|
|
590 |
|
|
|
591 |
<h4 id="events">Events?</h4> |
|
|
592 |
|
|
|
593 |
<p> |
|
|
594 |
Events are used to create a relationship between two objects, and better |
|
|
595 |
represent an open communication channel. Promises represent single values, |
|
|
596 |
and chains encapsulate transactions. |
|
|
597 |
</p> |
|
|
598 |
|
|
|
599 |
<p> |
|
|
600 |
It's not uncommon to have event subscribers launch a promise chain, or to |
|
|
601 |
have events fired from within operations inside a promise chain. They are |
|
|
602 |
complementary tools. |
|
|
603 |
</p> |
|
|
604 |
|
|
|
605 |
<h4 id="yasyncqueue"><code>Y.AsyncQueue</code></h4> |
|
|
606 |
|
|
|
607 |
<p> |
|
|
608 |
<code>Y.AsyncQueue</code> is a tool for splitting up long synchronous operations into |
|
|
609 |
asynchronous chunks to avoid blocking UI updates unnecessarily. It doesn't |
|
|
610 |
(as yet) support asynchronous steps. It also supports conditional looping |
|
|
611 |
and various other things that promises don't, out of the box. |
|
|
612 |
</p> |
|
|
613 |
|
|
|
614 |
<h4 id="yparallel"><code>Y.Parallel</code></h4> |
|
|
615 |
|
|
|
616 |
<p> |
|
|
617 |
<code>Y.Parallel</code> is similar to <code>Y.batch</code> in that it provides a mechanism to |
|
|
618 |
execute a callback when several independent asynchronous operations have |
|
|
619 |
completed. However, it doesn't handle errors or guarantee asynchronous |
|
|
620 |
callback execution. It is also transactional, but the batch of operations |
|
|
621 |
is bound to a specific callback, where <code>Y.batch()</code> returns a promise that |
|
|
622 |
represents the aggregated values of those operations. The promise can be |
|
|
623 |
used by multiple consumers if necessary. |
|
|
624 |
</p> |
|
|
625 |
|
|
|
626 |
<h3 id="plans">What are the plans for Promises in the library?</h3> |
|
|
627 |
|
|
|
628 |
<p> |
|
|
629 |
There are a lot of opportunities inside YUI to move transactional APIs to |
|
|
630 |
consume and/or return promises rather than use callbacks or one-time |
|
|
631 |
events. While there are no set plans for which APIs will be changed or in |
|
|
632 |
what priority order, you can expect to see promises showing up across the |
|
|
633 |
library in the near future. |
|
|
634 |
</p> |
|
|
635 |
</div> |
|
|
636 |
</div> |
|
|
637 |
</div> |
|
|
638 |
|
|
|
639 |
<div class="yui3-u-1-4"> |
|
|
640 |
<div class="sidebar"> |
|
|
641 |
|
|
|
642 |
<div id="toc" class="sidebox"> |
|
|
643 |
<div class="hd"> |
|
|
644 |
<h2 class="no-toc">Table of Contents</h2> |
|
|
645 |
</div> |
|
|
646 |
|
|
|
647 |
<div class="bd"> |
|
|
648 |
<ul class="toc"> |
|
|
649 |
<li> |
|
|
650 |
<a href="#getting-started">Getting Started</a> |
|
|
651 |
</li> |
|
|
652 |
<li> |
|
|
653 |
<a href="#the-basics">The Basics</a> |
|
|
654 |
<ul class="toc"> |
|
|
655 |
<li> |
|
|
656 |
<a href="#two-simple-methods">Two Simple Methods</a> |
|
|
657 |
</li> |
|
|
658 |
<li> |
|
|
659 |
<a href="#creating-a-promise">Creating a Promise</a> |
|
|
660 |
</li> |
|
|
661 |
<li> |
|
|
662 |
<a href="#resolving-a-promise">Resolving a Promise</a> |
|
|
663 |
</li> |
|
|
664 |
<li> |
|
|
665 |
<a href="#getting-the-promised-value">Getting the Promised Value</a> |
|
|
666 |
<ul class="toc"> |
|
|
667 |
<li> |
|
|
668 |
<a href="#always-asynchronous">Always Asynchronous</a> |
|
|
669 |
</li> |
|
|
670 |
</ul> |
|
|
671 |
</li> |
|
|
672 |
</ul> |
|
|
673 |
</li> |
|
|
674 |
<li> |
|
|
675 |
<a href="#the-not-so-basics">The Not-so Basics</a> |
|
|
676 |
<ul class="toc"> |
|
|
677 |
<li> |
|
|
678 |
<a href="#promise-chaining">Promise Chaining</a> |
|
|
679 |
</li> |
|
|
680 |
<li> |
|
|
681 |
<a href="#handling-errors">Handling Errors</a> |
|
|
682 |
<ul class="toc"> |
|
|
683 |
<li> |
|
|
684 |
<a href="#caveat-the-unhandled-rejection">Caveat: The Unhandled Rejection</a> |
|
|
685 |
</li> |
|
|
686 |
</ul> |
|
|
687 |
</li> |
|
|
688 |
<li> |
|
|
689 |
<a href="#omitting-onfulfilled-or-onrejected">Omitting <code>onFulfilled</code> or <code>onRejected</code></a> |
|
|
690 |
</li> |
|
|
691 |
<li> |
|
|
692 |
<a href="#chaining-asynchronous-operations">Chaining Asynchronous Operations</a> |
|
|
693 |
</li> |
|
|
694 |
<li> |
|
|
695 |
<a href="#ywhen-for-promise-wrapping"><code>Y.when()</code> For Promise Wrapping</a> |
|
|
696 |
</li> |
|
|
697 |
<li> |
|
|
698 |
<a href="#non-serial-operation-batching">Non-serial Operation Batching</a> |
|
|
699 |
</li> |
|
|
700 |
</ul> |
|
|
701 |
</li> |
|
|
702 |
<li> |
|
|
703 |
<a href="#faq">FAQ</a> |
|
|
704 |
<ul class="toc"> |
|
|
705 |
<li> |
|
|
706 |
<a href="#diff">What's the difference between <code>Y.Promise</code> and...</a> |
|
|
707 |
<ul class="toc"> |
|
|
708 |
<li> |
|
|
709 |
<a href="#events">Events?</a> |
|
|
710 |
</li> |
|
|
711 |
<li> |
|
|
712 |
<a href="#yasyncqueue"><code>Y.AsyncQueue</code></a> |
|
|
713 |
</li> |
|
|
714 |
<li> |
|
|
715 |
<a href="#yparallel"><code>Y.Parallel</code></a> |
|
|
716 |
</li> |
|
|
717 |
</ul> |
|
|
718 |
</li> |
|
|
719 |
<li> |
|
|
720 |
<a href="#plans">What are the plans for Promises in the library?</a> |
|
|
721 |
</li> |
|
|
722 |
</ul> |
|
|
723 |
</li> |
|
|
724 |
</ul> |
|
|
725 |
</div> |
|
|
726 |
</div> |
|
|
727 |
|
|
|
728 |
|
|
|
729 |
|
|
|
730 |
<div class="sidebox"> |
|
|
731 |
<div class="hd"> |
|
|
732 |
<h2 class="no-toc">Examples</h2> |
|
|
733 |
</div> |
|
|
734 |
|
|
|
735 |
<div class="bd"> |
|
|
736 |
<ul class="examples"> |
|
|
737 |
|
|
|
738 |
|
|
|
739 |
<li data-description="Wrapping async transactions with promises"> |
|
|
740 |
<a href="basic-example.html">Wrapping async transactions with promises</a> |
|
|
741 |
</li> |
|
|
742 |
|
|
|
743 |
|
|
|
744 |
|
|
|
745 |
<li data-description="Extend Y.Promise to create classes that encapsulate standard transaction logic in descriptive method names"> |
|
|
746 |
<a href="subclass-example.html">Subclassing Y.Promise</a> |
|
|
747 |
</li> |
|
|
748 |
|
|
|
749 |
|
|
|
750 |
|
|
|
751 |
<li data-description="Extend the Promise class to create your own Node plugin that chains transitions"> |
|
|
752 |
<a href="plugin-example.html">Creating a Node Plugin that chains transitions</a> |
|
|
753 |
</li> |
|
|
754 |
|
|
|
755 |
|
|
|
756 |
</ul> |
|
|
757 |
</div> |
|
|
758 |
</div> |
|
|
759 |
|
|
|
760 |
|
|
|
761 |
|
|
|
762 |
</div> |
|
|
763 |
</div> |
|
|
764 |
</div> |
|
|
765 |
</div> |
|
|
766 |
|
|
|
767 |
<script src="../assets/vendor/prettify/prettify-min.js"></script> |
|
|
768 |
<script>prettyPrint();</script> |
|
|
769 |
|
|
|
770 |
<script> |
|
|
771 |
YUI.Env.Tests = { |
|
|
772 |
examples: [], |
|
|
773 |
project: '../assets', |
|
|
774 |
assets: '../assets/promise', |
|
|
775 |
name: 'promise', |
|
|
776 |
title: 'Promise', |
|
|
777 |
newWindow: '', |
|
|
778 |
auto: false |
|
|
779 |
}; |
|
|
780 |
YUI.Env.Tests.examples.push('basic-example'); |
|
|
781 |
YUI.Env.Tests.examples.push('subclass-example'); |
|
|
782 |
YUI.Env.Tests.examples.push('plugin-example'); |
|
|
783 |
|
|
|
784 |
</script> |
|
|
785 |
<script src="../assets/yui/test-runner.js"></script> |
|
|
786 |
|
|
|
787 |
|
|
|
788 |
|
|
|
789 |
</body> |
|
|
790 |
</html> |