forked from dojo/dojo-oldmirror
-
Notifications
You must be signed in to change notification settings - Fork 0
/
when.js
52 lines (48 loc) · 1.75 KB
/
when.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
define([
"./Deferred",
"./promise/Promise"
], function(Deferred, Promise){
"use strict";
// module:
// dojo/when
return function when(valueOrPromise, /*Function?*/ callback, /*Function?*/ errback, /*Function?*/ progback){
// summary:
// Transparently applies callbacks to values and/or promises.
// description:
// Accepts promises but also transparently handles non-promises. If no
// callbacks are provided returns a promise, regardless of the initial
// value. Foreign promises are converted.
// If callbacks are provided and the initial value is not a promise,
// the callback is executed immediately with no error handling. Returns
// a promise if the initial value is a promise, or the result of the
// callback otherwise.
// returns: dojo/promise/Promise
//
// valueOrPromise:
// Either a regular value or a promise.
// callback:
// Callback to be invoked when the promise is resolved, or a non-promise
// is received.
// errback:
// Callback to be invoked when the promise is rejected.
// progback:
// Callback to be invoked when the promise emits a progress update.
var receivedPromise = valueOrPromise && typeof valueOrPromise.then === "function";
var nativePromise = receivedPromise && valueOrPromise instanceof Promise;
if(!receivedPromise){
if(callback){
return callback(valueOrPromise);
}else{
return new Deferred().resolve(valueOrPromise);
}
}else if(!nativePromise){
var deferred = new Deferred(valueOrPromise.cancel);
valueOrPromise.then(deferred.resolve, deferred.reject, deferred.progress);
valueOrPromise = deferred.promise;
}
if(callback || errback || progback){
return valueOrPromise.then(callback, errback, progback);
}
return valueOrPromise;
};
});