-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathPromise.lib.nut
374 lines (333 loc) · 12.1 KB
/
Promise.lib.nut
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
// MIT License
//
// Copyright 2020-23 KOIRE Wireless
// Copyright 2016-19 Electric Imp
// Copyright 2015 SMS Diagnostics Pty Ltd
//
// SPDX-License-Identifier: MIT
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// Error messages
const PROMISE_ERR_UNHANDLED_REJ = "Unhandled promise rejection: ";
// Promises for Electric Imp/Squirrel
class Promise {
static VERSION = "4.0.1";
static STATE_PENDING = 0;
static STATE_FULFILLED = 1;
static STATE_REJECTED = 2;
_state = null;
_value = null;
_last = null;
// @var {{resolve, reject}[]} _handlers
_handlers = null;
//
// @param {function(resolve, reject)} action - action function
//
constructor(action) {
_state = STATE_PENDING;
_last = true;
_handlers = [];
try {
action(
_resolve.bindenv(this)
_reject.bindenv(this)
);
} catch (e) {
_reject(e);
}
}
//
// Execute chain of handlers
//
function _callHandlers() {
if (STATE_PENDING != _state) {
imp.wakeup(0, function() {
if (_last && _handlers.len() == 0 && STATE_REJECTED == _state) {
server.log(PROMISE_ERR_UNHANDLED_REJ + _value);
}
foreach (handler in _handlers) {
(function (handler) { // create closure and bind handler to it
if (_state == STATE_FULFILLED) {
try {
handler.resolve(handler.onFulfilled(_value));
} catch (err) {
handler.reject(err);
}
} else if (_state == STATE_REJECTED) {
try {
handler.resolve(handler.onRejected(_value));
} catch (err) {
handler.reject(err);
}
}
})(handler);
}
_handlers = [];
}.bindenv(this));
}
}
//
// Resolve promise with a value
//
function _resolve(value = null) {
if (STATE_PENDING == _state) {
// If promise is resolved with another promise let it resolve/reject
// this one, otherwise resolve immediately
if (_isPromise(value)) {
value.then(
_resolve.bindenv(this),
_reject.bindenv(this)
);
} else {
_state = STATE_FULFILLED;
_value = value;
_callHandlers();
}
}
}
//
// Reject promise for a reason
//
function _reject(reason = null) {
if (STATE_PENDING == _state) {
_state = STATE_REJECTED;
_value = reason;
_callHandlers();
}
}
//
// Check if a value is a Promise.
// @param {Promise|*} value
// @return {boolean}
//
function _isPromise(value) {
if (// detect that the value is some form of Promise
// by the fact it has .then() method
(typeof value == "instance") &&
("then" in value) &&
(typeof value.then == "function")){
return true;
}
return false;
}
//
// Add handlers on resolve/rejection
// @param {function|null} onFulfilled
// @param {function|null} onRejected
// @return {this}
//
function then(onFulfilled = null, onRejected = null) {
// If either handler is left null, set it to our default handlers
onFulfilled = (typeof onFulfilled == "function") ? onFulfilled : Promise._onFulfilled;
onRejected = (typeof onRejected == "function") ? onRejected : Promise._onRejected;
local self = this;
_last = false;
local result = Promise(function(resolve, reject) {
self._handlers.push({
"resolve": resolve.bindenv(this),
"onFulfilled": onFulfilled,
"reject": reject.bindenv(this),
"onRejected": onRejected
});
});
_callHandlers();
return result;
}
//
// Add handler on rejection
// @param {function} onRejected
// @return {this}
//
function fail(onRejected) {
return then(null, onRejected);
}
//
// Add handler that is executed both on resolve and rejection
// @param {function(value)} handler
// @return {this}
//
function finally(handler) {
return then(handler, handler);
}
//
// The default `onFulfilled` handler (the identity function)
//
static function _onFulfilled(value) {
return value;
}
//
// The default rejection handler, just throws to the next handler
//
static function _onRejected(reason) {
throw reason;
}
//
// While loop with Promise's
// Stops on continueCallback() == false or first rejection of looped Promise
//
// @param {function:boolean} condition - if returns false, loop stops
// @param {function:Promise} next - function to get next promise in the loop
// @return {Promise} Promise that is resolved/rejected with the last value that come from looped promise when loop finishes
//
static function loop(condition, next) {
return Promise(function (resolve, reject) {
local doLoop;
local lastResolvedWith;
doLoop = function() {
if (condition()) {
next().then(
function (v) {
lastResolvedWith = v;
imp.wakeup(0, doLoop);
},
reject
);
} else {
resolve(lastResolvedWith);
}
}
imp.wakeup(0, doLoop);
}.bindenv(this));
}
//
// Returns Promise that resolves when
// all promises in chain resolve:
// one after each other.
// Make every promise in array of promises not last
// for suppressing Unhadled Exeptions Warnings
//
// FROM 4.0.1 -- Update function to avoid calling 'array[any exp.]()' as
// identified by @gjanvier, and to check for non-array params
//
// @param {{Promise|function}[]} promises - array of Promises/functions that return Promises
// @return {Promise} Promise that is resolved/rejected with the last value that come from looped promise
//
static function serial(promises) {
// FROM 4.0.1
// Check we at least have an array -- return an auto-reject Promise if not
if (typeof promises != "array") {
return Promise.reject("Promise.serial() not passed an array");
}
local i = 0;
return loop(
// This is a Squirrel lambda --
// see https://developer.electricimp.com/squirrel/squirrel-guide/functions#lambda-functions
@() i < promises.len(),
// FROM 4.0.1
// Implement fix for this reported issue (#24):
// https://forums.electricimp.com/t/my-integer-suddenly-becomes-a-string/6454/7
function () {
local nextFunction = promises[i++];
if ("function" == typeof nextFunction) {
// Return function call -- it should return
// a promise
return nextFunction();
} else {
// Return a promise
return nextFunction;
}
}
)
}
//
// Returns Promise that resolves when all promises in the list resolve
//
// @param {{Promise}[]} promises - array of Promises (or functions that
// return promises)
// @param {boolean} wait - whether to wait for all promises to resolve, or
// just the first
// @return {Promise} Promise that is resolved with the list of values that
// `promises` resolved to (in order) OR with the value of the first promise
// that resolves (depending on `wait`)
//
static function _parallel(promises, wait) {
return Promise(function(resolve, reject) {
local resolved = 0; // number of promises resolved
local len = promises.len(); // number of promises given
local result = array(len); // results array (for if we're waiting for all to resolve)
// early return/resolve for case when `promises` is empty
if (!len) return resolve(result);
// resolve one promise with a value
local resolveOne = function(index, value) {
if (!wait) {
// early return if we're not waiting for all to resolve
return resolve(value);
}
result[index] = value;
resolved += 1;
if (resolved == len) {
resolve(result);
}
};
foreach (index, promise in promises) {
promise = (typeof promise == "function") ? promise() : promise;
(function(index) {
promise.then(function(value) {
resolveOne(index, value);
}.bindenv(this), reject);
}.bindenv(this))(index);
}
}.bindenv(this));
}
//
// Returns Promise that resolves to an array containing the results of each
// given promise (or rejects with the first rejected)
// @param {{Promise}[]} promises - array of Promises (or functions which
// return promises)
// @return {Promise} Promise that is resolved with the list of values that
// `promises` resolved to (in order) or rejects with the reason of the first
// of `promises` to reject
//
static function all(promises) {
return _parallel(promises, true);
}
//
// Returns Promise that resolves to the first value that any of the given
// promises resolve to
//
// @param {{Promise}[]} promises - array of Promises (or functions which
// return promises)
// @return {Promise} Promise that is resolved with the to the value of the
// first of `promises` to resolve (or rejects with the first to reject)
//
static function race(promises) {
return _parallel(promises, false);
}
//
// Returns promise that immediately resolves to the given value
//
// @param {*} value - value to resolve to
// @return {Promise} - a Promise that immediately resolves to `value`
//
static function resolve(value) {
return Promise(function(resolve, reject) {
resolve(value);
})
}
// Returns promise that immediately rejects with the given reason
//
// @param {*} value - value to resolve to
// @return {Promise} - a Promise that immediately rejects with `reason`
//
static function reject(reason) {
return Promise(function(resolve, reject) {
reject(reason);
})
}
}