UNPKG

1.19 kBJavaScriptView Raw
1/*
2 * Copyright 2013 the original author or authors
3 * @license MIT, see LICENSE.txt for details
4 *
5 * @author Scott Andrews
6 */
7
8(function (define) {
9 'use strict';
10
11 define(function (require) {
12
13 var when;
14
15 when = require('when');
16
17 /**
18 * Create a promise whose work is started only when a handler is registered.
19 *
20 * The work function will be invoked at most once. Thrown values will result
21 * in promise rejection.
22 *
23 * @param {Function} work function whose ouput is used to resolve the
24 * returned promise.
25 * @returns {Promise} a lazy promise
26 */
27 function lazyPromise(work) {
28 var defer, started, resolver, promise, then;
29
30 defer = when.defer();
31 started = false;
32
33 resolver = defer.resolver;
34 promise = defer.promise;
35 then = promise.then;
36
37 promise.then = function () {
38 if (!started) {
39 started = true;
40 when.attempt(work).then(resolver.resolve, resolver.reject);
41 }
42 return then.apply(promise, arguments);
43 };
44
45 return promise;
46 }
47
48 return lazyPromise;
49
50 });
51
52}(
53 typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); }
54 // Boilerplate for AMD and Node
55));