Best JavaScript code snippet using playwright-internal
es6-promise-dbg.js
Source:es6-promise-dbg.js
...28 var lib$es6$promise$asap$$len = 0;29 var lib$es6$promise$asap$$toString = {}.toString;30 var lib$es6$promise$asap$$vertxNext;31 var lib$es6$promise$asap$$customSchedulerFn;32 var lib$es6$promise$asap$$asap = function asap(callback, arg) {33 lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;34 lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;35 lib$es6$promise$asap$$len += 2;36 if (lib$es6$promise$asap$$len === 2) {37 // If len is 2, that means that we need to schedule an async flush.38 // If additional callbacks are queued before the queue is flushed, they39 // will be processed by this flush that we are scheduling.40 if (lib$es6$promise$asap$$customSchedulerFn) {41 lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);42 } else {43 lib$es6$promise$asap$$scheduleFlush();44 }45 }46 }47 function lib$es6$promise$asap$$setScheduler(scheduleFn) {48 lib$es6$promise$asap$$customSchedulerFn = scheduleFn;49 }50 function lib$es6$promise$asap$$setAsap(asapFn) {51 lib$es6$promise$asap$$asap = asapFn;52 }53 var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;54 var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};55 var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;56 var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';57 // test for web worker but not in IE1058 var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&59 typeof importScripts !== 'undefined' &&60 typeof MessageChannel !== 'undefined';61 // node62 function lib$es6$promise$asap$$useNextTick() {63 var nextTick = process.nextTick;64 // node version 0.10.x displays a deprecation warning when nextTick is used recursively65 // setImmediate should be used instead instead66 var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);67 if (Array.isArray(version) && version[1] === '0' && version[2] === '10') {68 nextTick = setImmediate;69 }70 return function() {71 nextTick(lib$es6$promise$asap$$flush);72 };73 }74 // vertx75 function lib$es6$promise$asap$$useVertxTimer() {76 return function() {77 lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);78 };79 }80 function lib$es6$promise$asap$$useMutationObserver() {81 var iterations = 0;82 var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);83 var node = document.createTextNode('');84 observer.observe(node, { characterData: true });85 return function() {86 node.data = (iterations = ++iterations % 2);87 };88 }89 // web worker90 function lib$es6$promise$asap$$useMessageChannel() {91 var channel = new MessageChannel();92 channel.port1.onmessage = lib$es6$promise$asap$$flush;93 return function () {94 channel.port2.postMessage(0);95 };96 }97 function lib$es6$promise$asap$$useSetTimeout() {98 return function() {99 setTimeout(lib$es6$promise$asap$$flush, 1);100 };101 }102 var lib$es6$promise$asap$$queue = new Array(1000);103 function lib$es6$promise$asap$$flush() {104 for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {105 var callback = lib$es6$promise$asap$$queue[i];106 var arg = lib$es6$promise$asap$$queue[i+1];107 callback(arg);108 lib$es6$promise$asap$$queue[i] = undefined;109 lib$es6$promise$asap$$queue[i+1] = undefined;110 }111 lib$es6$promise$asap$$len = 0;112 }113 function lib$es6$promise$asap$$attemptVertex() {114 try {115 var r = require;116 var vertx = r('vertx');117 lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;118 return lib$es6$promise$asap$$useVertxTimer();119 } catch(e) {120 return lib$es6$promise$asap$$useSetTimeout();121 }122 }123 var lib$es6$promise$asap$$scheduleFlush;124 // Decide what async method to use to triggering processing of queued callbacks:125 if (lib$es6$promise$asap$$isNode) {126 lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();127 } else if (lib$es6$promise$asap$$BrowserMutationObserver) {128 lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();129 } else if (lib$es6$promise$asap$$isWorker) {130 lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();131 } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {132 lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertex();133 } else {134 lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();135 }136 function lib$es6$promise$$internal$$noop() {}137 var lib$es6$promise$$internal$$PENDING = void 0;138 var lib$es6$promise$$internal$$FULFILLED = 1;139 var lib$es6$promise$$internal$$REJECTED = 2;140 var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();141 function lib$es6$promise$$internal$$selfFullfillment() {142 return new TypeError("You cannot resolve a promise with itself");143 }144 function lib$es6$promise$$internal$$cannotReturnOwn() {145 return new TypeError('A promises callback cannot return that same promise.');146 }147 function lib$es6$promise$$internal$$getThen(promise) {148 try {149 return promise.then;150 } catch(error) {151 lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;152 return lib$es6$promise$$internal$$GET_THEN_ERROR;153 }154 }155 function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {156 try {157 then.call(value, fulfillmentHandler, rejectionHandler);158 } catch(e) {159 return e;160 }161 }162 function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {163 lib$es6$promise$asap$$asap(function(promise) {164 var sealed = false;165 var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {166 if (sealed) { return; }167 sealed = true;168 if (thenable !== value) {169 lib$es6$promise$$internal$$resolve(promise, value);170 } else {171 lib$es6$promise$$internal$$fulfill(promise, value);172 }173 }, function(reason) {174 if (sealed) { return; }175 sealed = true;176 lib$es6$promise$$internal$$reject(promise, reason);177 }, 'Settle: ' + (promise._label || ' unknown promise'));178 if (!sealed && error) {179 sealed = true;180 lib$es6$promise$$internal$$reject(promise, error);181 }182 }, promise);183 }184 function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {185 if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {186 lib$es6$promise$$internal$$fulfill(promise, thenable._result);187 } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {188 lib$es6$promise$$internal$$reject(promise, thenable._result);189 } else {190 lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {191 lib$es6$promise$$internal$$resolve(promise, value);192 }, function(reason) {193 lib$es6$promise$$internal$$reject(promise, reason);194 });195 }196 }197 function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {198 if (maybeThenable.constructor === promise.constructor) {199 lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);200 } else {201 var then = lib$es6$promise$$internal$$getThen(maybeThenable);202 if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {203 lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);204 } else if (then === undefined) {205 lib$es6$promise$$internal$$fulfill(promise, maybeThenable);206 } else if (lib$es6$promise$utils$$isFunction(then)) {207 lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);208 } else {209 lib$es6$promise$$internal$$fulfill(promise, maybeThenable);210 }211 }212 }213 function lib$es6$promise$$internal$$resolve(promise, value) {214 if (promise === value) {215 lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment());216 } else if (lib$es6$promise$utils$$objectOrFunction(value)) {217 lib$es6$promise$$internal$$handleMaybeThenable(promise, value);218 } else {219 lib$es6$promise$$internal$$fulfill(promise, value);220 }221 }222 function lib$es6$promise$$internal$$publishRejection(promise) {223 if (promise._onerror) {224 promise._onerror(promise._result);225 }226 lib$es6$promise$$internal$$publish(promise);227 }228 function lib$es6$promise$$internal$$fulfill(promise, value) {229 if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }230 promise._result = value;231 promise._state = lib$es6$promise$$internal$$FULFILLED;232 if (promise._subscribers.length !== 0) {233 lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);234 }235 }236 function lib$es6$promise$$internal$$reject(promise, reason) {237 if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }238 promise._state = lib$es6$promise$$internal$$REJECTED;239 promise._result = reason;240 lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);241 }242 function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {243 var subscribers = parent._subscribers;244 var length = subscribers.length;245 parent._onerror = null;246 subscribers[length] = child;247 subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;248 subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;249 if (length === 0 && parent._state) {250 lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);251 }252 }253 function lib$es6$promise$$internal$$publish(promise) {254 var subscribers = promise._subscribers;255 var settled = promise._state;256 if (subscribers.length === 0) { return; }257 var child, callback, detail = promise._result;258 for (var i = 0; i < subscribers.length; i += 3) {259 child = subscribers[i];260 callback = subscribers[i + settled];261 if (child) {262 lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);263 } else {264 callback(detail);265 }266 }267 promise._subscribers.length = 0;268 }269 function lib$es6$promise$$internal$$ErrorObject() {270 this.error = null;271 }272 var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();273 function lib$es6$promise$$internal$$tryCatch(callback, detail) {274 try {275 return callback(detail);276 } catch(e) {277 lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;278 return lib$es6$promise$$internal$$TRY_CATCH_ERROR;279 }280 }281 function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {282 var hasCallback = lib$es6$promise$utils$$isFunction(callback),283 value, error, succeeded, failed;284 if (hasCallback) {285 value = lib$es6$promise$$internal$$tryCatch(callback, detail);286 if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {287 failed = true;288 error = value.error;289 value = null;290 } else {291 succeeded = true;292 }293 if (promise === value) {294 lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());295 return;296 }297 } else {298 value = detail;299 succeeded = true;300 }301 if (promise._state !== lib$es6$promise$$internal$$PENDING) {302 // noop303 } else if (hasCallback && succeeded) {304 lib$es6$promise$$internal$$resolve(promise, value);305 } else if (failed) {306 lib$es6$promise$$internal$$reject(promise, error);307 } else if (settled === lib$es6$promise$$internal$$FULFILLED) {308 lib$es6$promise$$internal$$fulfill(promise, value);309 } else if (settled === lib$es6$promise$$internal$$REJECTED) {310 lib$es6$promise$$internal$$reject(promise, value);311 }312 }313 function lib$es6$promise$$internal$$initializePromise(promise, resolver) {314 try {315 resolver(function resolvePromise(value){316 lib$es6$promise$$internal$$resolve(promise, value);317 }, function rejectPromise(reason) {318 lib$es6$promise$$internal$$reject(promise, reason);319 });320 } catch(e) {321 lib$es6$promise$$internal$$reject(promise, e);322 }323 }324 function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {325 var enumerator = this;326 enumerator._instanceConstructor = Constructor;327 enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);328 if (enumerator._validateInput(input)) {329 enumerator._input = input;330 enumerator.length = input.length;331 enumerator._remaining = input.length;332 enumerator._init();333 if (enumerator.length === 0) {334 lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);335 } else {336 enumerator.length = enumerator.length || 0;337 enumerator._enumerate();338 if (enumerator._remaining === 0) {339 lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);340 }341 }342 } else {343 lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());344 }345 }346 lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {347 return lib$es6$promise$utils$$isArray(input);348 };349 lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {350 return new Error('Array Methods must be provided an Array');351 };352 lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {353 this._result = new Array(this.length);354 };355 var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;356 lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {357 var enumerator = this;358 var length = enumerator.length;359 var promise = enumerator.promise;360 var input = enumerator._input;361 for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {362 enumerator._eachEntry(input[i], i);363 }364 };365 lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {366 var enumerator = this;367 var c = enumerator._instanceConstructor;368 if (lib$es6$promise$utils$$isMaybeThenable(entry)) {369 if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {370 entry._onerror = null;371 enumerator._settledAt(entry._state, i, entry._result);372 } else {373 enumerator._willSettleAt(c.resolve(entry), i);374 }375 } else {376 enumerator._remaining--;377 enumerator._result[i] = entry;378 }379 };380 lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {381 var enumerator = this;382 var promise = enumerator.promise;383 if (promise._state === lib$es6$promise$$internal$$PENDING) {384 enumerator._remaining--;385 if (state === lib$es6$promise$$internal$$REJECTED) {386 lib$es6$promise$$internal$$reject(promise, value);387 } else {388 enumerator._result[i] = value;389 }390 }391 if (enumerator._remaining === 0) {392 lib$es6$promise$$internal$$fulfill(promise, enumerator._result);393 }394 };395 lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {396 var enumerator = this;397 lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {398 enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);399 }, function(reason) {400 enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);401 });402 };403 function lib$es6$promise$promise$all$$all(entries) {404 return new lib$es6$promise$enumerator$$default(this, entries).promise;405 }406 var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;407 function lib$es6$promise$promise$race$$race(entries) {408 /*jshint validthis:true */409 var Constructor = this;410 var promise = new Constructor(lib$es6$promise$$internal$$noop);411 if (!lib$es6$promise$utils$$isArray(entries)) {412 lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));413 return promise;414 }415 var length = entries.length;416 function onFulfillment(value) {417 lib$es6$promise$$internal$$resolve(promise, value);418 }419 function onRejection(reason) {420 lib$es6$promise$$internal$$reject(promise, reason);421 }422 for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {423 lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);424 }425 return promise;426 }427 var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;428 function lib$es6$promise$promise$resolve$$resolve(object) {429 /*jshint validthis:true */430 var Constructor = this;431 if (object && typeof object === 'object' && object.constructor === Constructor) {432 return object;433 }434 var promise = new Constructor(lib$es6$promise$$internal$$noop);435 lib$es6$promise$$internal$$resolve(promise, object);436 return promise;437 }438 var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;439 function lib$es6$promise$promise$reject$$reject(reason) {440 /*jshint validthis:true */441 var Constructor = this;442 var promise = new Constructor(lib$es6$promise$$internal$$noop);443 lib$es6$promise$$internal$$reject(promise, reason);444 return promise;445 }446 var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;447 var lib$es6$promise$promise$$counter = 0;448 function lib$es6$promise$promise$$needsResolver() {449 throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');450 }451 function lib$es6$promise$promise$$needsNew() {452 throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");453 }454 var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;455 /**456 Promise objects represent the eventual result of an asynchronous operation. The457 primary way of interacting with a promise is through its `then` method, which458 registers callbacks to receive either a promise's eventual value or the reason459 why the promise cannot be fulfilled.460 Terminology461 -----------462 - `promise` is an object or function with a `then` method whose behavior conforms to this specification.463 - `thenable` is an object or function that defines a `then` method.464 - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).465 - `exception` is a value that is thrown using the throw statement.466 - `reason` is a value that indicates why a promise was rejected.467 - `settled` the final resting state of a promise, fulfilled or rejected.468 A promise can be in one of three states: pending, fulfilled, or rejected.469 Promises that are fulfilled have a fulfillment value and are in the fulfilled470 state. Promises that are rejected have a rejection reason and are in the471 rejected state. A fulfillment value is never a thenable.472 Promises can also be said to *resolve* a value. If this value is also a473 promise, then the original promise's settled state will match the value's474 settled state. So a promise that *resolves* a promise that rejects will475 itself reject, and a promise that *resolves* a promise that fulfills will476 itself fulfill.477 Basic Usage:478 ------------479 ```js480 var promise = new Promise(function(resolve, reject) {481 // on success482 resolve(value);483 // on failure484 reject(reason);485 });486 promise.then(function(value) {487 // on fulfillment488 }, function(reason) {489 // on rejection490 });491 ```492 Advanced Usage:493 ---------------494 Promises shine when abstracting away asynchronous interactions such as495 `XMLHttpRequest`s.496 ```js497 function getJSON(url) {498 return new Promise(function(resolve, reject){499 var xhr = new XMLHttpRequest();500 xhr.open('GET', url);501 xhr.onreadystatechange = handler;502 xhr.responseType = 'json';503 xhr.setRequestHeader('Accept', 'application/json');504 xhr.send();505 function handler() {506 if (this.readyState === this.DONE) {507 if (this.status === 200) {508 resolve(this.response);509 } else {510 reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));511 }512 }513 };514 });515 }516 getJSON('/posts.json').then(function(json) {517 // on fulfillment518 }, function(reason) {519 // on rejection520 });521 ```522 Unlike callbacks, promises are great composable primitives.523 ```js524 Promise.all([525 getJSON('/posts'),526 getJSON('/comments')527 ]).then(function(values){528 values[0] // => postsJSON529 values[1] // => commentsJSON530 return values;531 });532 ```533 @class Promise534 @param {function} resolver535 Useful for tooling.536 @constructor537 */538 function lib$es6$promise$promise$$Promise(resolver) {539 this._id = lib$es6$promise$promise$$counter++;540 this._state = undefined;541 this._result = undefined;542 this._subscribers = [];543 if (lib$es6$promise$$internal$$noop !== resolver) {544 if (!lib$es6$promise$utils$$isFunction(resolver)) {545 lib$es6$promise$promise$$needsResolver();546 }547 if (!(this instanceof lib$es6$promise$promise$$Promise)) {548 lib$es6$promise$promise$$needsNew();549 }550 lib$es6$promise$$internal$$initializePromise(this, resolver);551 }552 }553 lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;554 lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;555 lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;556 lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;557 lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;558 lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;559 lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;560 lib$es6$promise$promise$$Promise.prototype = {561 constructor: lib$es6$promise$promise$$Promise,562 /**563 The primary way of interacting with a promise is through its `then` method,564 which registers callbacks to receive either a promise's eventual value or the565 reason why the promise cannot be fulfilled.566 ```js567 findUser().then(function(user){568 // user is available569 }, function(reason){570 // user is unavailable, and you are given the reason why571 });572 ```573 Chaining574 --------575 The return value of `then` is itself a promise. This second, 'downstream'576 promise is resolved with the return value of the first promise's fulfillment577 or rejection handler, or rejected if the handler throws an exception.578 ```js579 findUser().then(function (user) {580 return user.name;581 }, function (reason) {582 return 'default name';583 }).then(function (userName) {584 // If `findUser` fulfilled, `userName` will be the user's name, otherwise it585 // will be `'default name'`586 });587 findUser().then(function (user) {588 throw new Error('Found user, but still unhappy');589 }, function (reason) {590 throw new Error('`findUser` rejected and we're unhappy');591 }).then(function (value) {592 // never reached593 }, function (reason) {594 // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.595 // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.596 });597 ```598 If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.599 ```js600 findUser().then(function (user) {601 throw new PedagogicalException('Upstream error');602 }).then(function (value) {603 // never reached604 }).then(function (value) {605 // never reached606 }, function (reason) {607 // The `PedgagocialException` is propagated all the way down to here608 });609 ```610 Assimilation611 ------------612 Sometimes the value you want to propagate to a downstream promise can only be613 retrieved asynchronously. This can be achieved by returning a promise in the614 fulfillment or rejection handler. The downstream promise will then be pending615 until the returned promise is settled. This is called *assimilation*.616 ```js617 findUser().then(function (user) {618 return findCommentsByAuthor(user);619 }).then(function (comments) {620 // The user's comments are now available621 });622 ```623 If the assimliated promise rejects, then the downstream promise will also reject.624 ```js625 findUser().then(function (user) {626 return findCommentsByAuthor(user);627 }).then(function (comments) {628 // If `findCommentsByAuthor` fulfills, we'll have the value here629 }, function (reason) {630 // If `findCommentsByAuthor` rejects, we'll have the reason here631 });632 ```633 Simple Example634 --------------635 Synchronous Example636 ```javascript637 var result;638 try {639 result = findResult();640 // success641 } catch(reason) {642 // failure643 }644 ```645 Errback Example646 ```js647 findResult(function(result, err){648 if (err) {649 // failure650 } else {651 // success652 }653 });654 ```655 Promise Example;656 ```javascript657 findResult().then(function(result){658 // success659 }, function(reason){660 // failure661 });662 ```663 Advanced Example664 --------------665 Synchronous Example666 ```javascript667 var author, books;668 try {669 author = findAuthor();670 books = findBooksByAuthor(author);671 // success672 } catch(reason) {673 // failure674 }675 ```676 Errback Example677 ```js678 function foundBooks(books) {679 }680 function failure(reason) {681 }682 findAuthor(function(author, err){683 if (err) {684 failure(err);685 // failure686 } else {687 try {688 findBoooksByAuthor(author, function(books, err) {689 if (err) {690 failure(err);691 } else {692 try {693 foundBooks(books);694 } catch(reason) {695 failure(reason);696 }697 }698 });699 } catch(error) {700 failure(err);701 }702 // success703 }704 });705 ```706 Promise Example;707 ```javascript708 findAuthor().709 then(findBooksByAuthor).710 then(function(books){711 // found books712 }).catch(function(reason){713 // something went wrong714 });715 ```716 @method then717 @param {Function} onFulfilled718 @param {Function} onRejected719 Useful for tooling.720 @return {Promise}721 */722 then: function(onFulfillment, onRejection) {723 var parent = this;724 var state = parent._state;725 if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {726 return this;727 }728 var child = new this.constructor(lib$es6$promise$$internal$$noop);729 var result = parent._result;730 if (state) {731 var callback = arguments[state - 1];732 lib$es6$promise$asap$$asap(function(){733 lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);734 });735 } else {736 lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);737 }738 return child;739 },740 /**741 `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same742 as the catch block of a try/catch statement.743 ```js744 function findAuthor(){745 throw new Error('couldn't find that author');746 }...
promise.js
Source:promise.js
...28 var lib$es6$promise$asap$$len = 0;29 var lib$es6$promise$asap$$toString = {}.toString;30 var lib$es6$promise$asap$$vertxNext;31 var lib$es6$promise$asap$$customSchedulerFn;32 function lib$es6$promise$asap$$asap(callback, arg) {33 lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;34 lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;35 lib$es6$promise$asap$$len += 2;36 if (lib$es6$promise$asap$$len === 2) {37 // If len is 2, that means that we need to schedule an async flush.38 // If additional callbacks are queued before the queue is flushed, they39 // will be processed by this flush that we are scheduling.40 if (lib$es6$promise$asap$$customSchedulerFn) {41 lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);42 } else {43 lib$es6$promise$asap$$scheduleFlush();44 }45 }46 }...
es6-promise.js
Source:es6-promise.js
...28 var lib$es6$promise$asap$$len = 0;29 var lib$es6$promise$asap$$toString = {}.toString;30 var lib$es6$promise$asap$$vertxNext;31 var lib$es6$promise$asap$$customSchedulerFn;32 var lib$es6$promise$asap$$asap = function asap(callback, arg) {33 lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;34 lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;35 lib$es6$promise$asap$$len += 2;36 if (lib$es6$promise$asap$$len === 2) {37 // If len is 2, that means that we need to schedule an async flush.38 // If additional callbacks are queued before the queue is flushed, they39 // will be processed by this flush that we are scheduling.40 if (lib$es6$promise$asap$$customSchedulerFn) {41 lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);42 } else {43 lib$es6$promise$asap$$scheduleFlush();44 }45 }46 }47 function lib$es6$promise$asap$$setScheduler(scheduleFn) {48 lib$es6$promise$asap$$customSchedulerFn = scheduleFn;49 }50 function lib$es6$promise$asap$$setAsap(asapFn) {51 lib$es6$promise$asap$$asap = asapFn;52 }53 var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;54 var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};55 var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;56 var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';57 // test for web worker but not in IE1058 var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&59 typeof importScripts !== 'undefined' &&60 typeof MessageChannel !== 'undefined';61 // node62 function lib$es6$promise$asap$$useNextTick() {63 // node version 0.10.x displays a deprecation warning when nextTick is used recursively64 // see https://github.com/cujojs/when/issues/410 for details65 return function() {66 process.nextTick(lib$es6$promise$asap$$flush);67 };68 }69 // vertx70 function lib$es6$promise$asap$$useVertxTimer() {71 return function() {72 lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);73 };74 }75 function lib$es6$promise$asap$$useMutationObserver() {76 var iterations = 0;77 var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);78 var node = document.createTextNode('');79 observer.observe(node, { characterData: true });80 return function() {81 node.data = (iterations = ++iterations % 2);82 };83 }84 // web worker85 function lib$es6$promise$asap$$useMessageChannel() {86 var channel = new MessageChannel();87 channel.port1.onmessage = lib$es6$promise$asap$$flush;88 return function () {89 channel.port2.postMessage(0);90 };91 }92 function lib$es6$promise$asap$$useSetTimeout() {93 return function() {94 setTimeout(lib$es6$promise$asap$$flush, 1);95 };96 }97 var lib$es6$promise$asap$$queue = new Array(1000);98 function lib$es6$promise$asap$$flush() {99 for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {100 var callback = lib$es6$promise$asap$$queue[i];101 var arg = lib$es6$promise$asap$$queue[i+1];102 callback(arg);103 lib$es6$promise$asap$$queue[i] = undefined;104 lib$es6$promise$asap$$queue[i+1] = undefined;105 }106 lib$es6$promise$asap$$len = 0;107 }108 function lib$es6$promise$asap$$attemptVertx() {109 try {110 var r = require;111 var vertx = r('vertx');112 lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;113 return lib$es6$promise$asap$$useVertxTimer();114 } catch(e) {115 return lib$es6$promise$asap$$useSetTimeout();116 }117 }118 var lib$es6$promise$asap$$scheduleFlush;119 // Decide what async method to use to triggering processing of queued callbacks:120 if (lib$es6$promise$asap$$isNode) {121 lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();122 } else if (lib$es6$promise$asap$$BrowserMutationObserver) {123 lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();124 } else if (lib$es6$promise$asap$$isWorker) {125 lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();126 } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {127 lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();128 } else {129 lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();130 }131 function lib$es6$promise$$internal$$noop() {}132 var lib$es6$promise$$internal$$PENDING = void 0;133 var lib$es6$promise$$internal$$FULFILLED = 1;134 var lib$es6$promise$$internal$$REJECTED = 2;135 var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();136 function lib$es6$promise$$internal$$selfFulfillment() {137 return new TypeError("You cannot resolve a promise with itself");138 }139 function lib$es6$promise$$internal$$cannotReturnOwn() {140 return new TypeError('A promises callback cannot return that same promise.');141 }142 function lib$es6$promise$$internal$$getThen(promise) {143 try {144 return promise.then;145 } catch(error) {146 lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;147 return lib$es6$promise$$internal$$GET_THEN_ERROR;148 }149 }150 function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {151 try {152 then.call(value, fulfillmentHandler, rejectionHandler);153 } catch(e) {154 return e;155 }156 }157 function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {158 lib$es6$promise$asap$$asap(function(promise) {159 var sealed = false;160 var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {161 if (sealed) { return; }162 sealed = true;163 if (thenable !== value) {164 lib$es6$promise$$internal$$resolve(promise, value);165 } else {166 lib$es6$promise$$internal$$fulfill(promise, value);167 }168 }, function(reason) {169 if (sealed) { return; }170 sealed = true;171 lib$es6$promise$$internal$$reject(promise, reason);172 }, 'Settle: ' + (promise._label || ' unknown promise'));173 if (!sealed && error) {174 sealed = true;175 lib$es6$promise$$internal$$reject(promise, error);176 }177 }, promise);178 }179 function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {180 if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {181 lib$es6$promise$$internal$$fulfill(promise, thenable._result);182 } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {183 lib$es6$promise$$internal$$reject(promise, thenable._result);184 } else {185 lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {186 lib$es6$promise$$internal$$resolve(promise, value);187 }, function(reason) {188 lib$es6$promise$$internal$$reject(promise, reason);189 });190 }191 }192 function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {193 if (maybeThenable.constructor === promise.constructor) {194 lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);195 } else {196 var then = lib$es6$promise$$internal$$getThen(maybeThenable);197 if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {198 lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);199 } else if (then === undefined) {200 lib$es6$promise$$internal$$fulfill(promise, maybeThenable);201 } else if (lib$es6$promise$utils$$isFunction(then)) {202 lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);203 } else {204 lib$es6$promise$$internal$$fulfill(promise, maybeThenable);205 }206 }207 }208 function lib$es6$promise$$internal$$resolve(promise, value) {209 if (promise === value) {210 lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());211 } else if (lib$es6$promise$utils$$objectOrFunction(value)) {212 lib$es6$promise$$internal$$handleMaybeThenable(promise, value);213 } else {214 lib$es6$promise$$internal$$fulfill(promise, value);215 }216 }217 function lib$es6$promise$$internal$$publishRejection(promise) {218 if (promise._onerror) {219 promise._onerror(promise._result);220 }221 lib$es6$promise$$internal$$publish(promise);222 }223 function lib$es6$promise$$internal$$fulfill(promise, value) {224 if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }225 promise._result = value;226 promise._state = lib$es6$promise$$internal$$FULFILLED;227 if (promise._subscribers.length !== 0) {228 lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);229 }230 }231 function lib$es6$promise$$internal$$reject(promise, reason) {232 if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }233 promise._state = lib$es6$promise$$internal$$REJECTED;234 promise._result = reason;235 lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);236 }237 function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {238 var subscribers = parent._subscribers;239 var length = subscribers.length;240 parent._onerror = null;241 subscribers[length] = child;242 subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;243 subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;244 if (length === 0 && parent._state) {245 lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);246 }247 }248 function lib$es6$promise$$internal$$publish(promise) {249 var subscribers = promise._subscribers;250 var settled = promise._state;251 if (subscribers.length === 0) { return; }252 var child, callback, detail = promise._result;253 for (var i = 0; i < subscribers.length; i += 3) {254 child = subscribers[i];255 callback = subscribers[i + settled];256 if (child) {257 lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);258 } else {259 callback(detail);260 }261 }262 promise._subscribers.length = 0;263 }264 function lib$es6$promise$$internal$$ErrorObject() {265 this.error = null;266 }267 var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();268 function lib$es6$promise$$internal$$tryCatch(callback, detail) {269 try {270 return callback(detail);271 } catch(e) {272 lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;273 return lib$es6$promise$$internal$$TRY_CATCH_ERROR;274 }275 }276 function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {277 var hasCallback = lib$es6$promise$utils$$isFunction(callback),278 value, error, succeeded, failed;279 if (hasCallback) {280 value = lib$es6$promise$$internal$$tryCatch(callback, detail);281 if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {282 failed = true;283 error = value.error;284 value = null;285 } else {286 succeeded = true;287 }288 if (promise === value) {289 lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());290 return;291 }292 } else {293 value = detail;294 succeeded = true;295 }296 if (promise._state !== lib$es6$promise$$internal$$PENDING) {297 // noop298 } else if (hasCallback && succeeded) {299 lib$es6$promise$$internal$$resolve(promise, value);300 } else if (failed) {301 lib$es6$promise$$internal$$reject(promise, error);302 } else if (settled === lib$es6$promise$$internal$$FULFILLED) {303 lib$es6$promise$$internal$$fulfill(promise, value);304 } else if (settled === lib$es6$promise$$internal$$REJECTED) {305 lib$es6$promise$$internal$$reject(promise, value);306 }307 }308 function lib$es6$promise$$internal$$initializePromise(promise, resolver) {309 try {310 resolver(function resolvePromise(value){311 lib$es6$promise$$internal$$resolve(promise, value);312 }, function rejectPromise(reason) {313 lib$es6$promise$$internal$$reject(promise, reason);314 });315 } catch(e) {316 lib$es6$promise$$internal$$reject(promise, e);317 }318 }319 function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {320 var enumerator = this;321 enumerator._instanceConstructor = Constructor;322 enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);323 if (enumerator._validateInput(input)) {324 enumerator._input = input;325 enumerator.length = input.length;326 enumerator._remaining = input.length;327 enumerator._init();328 if (enumerator.length === 0) {329 lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);330 } else {331 enumerator.length = enumerator.length || 0;332 enumerator._enumerate();333 if (enumerator._remaining === 0) {334 lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);335 }336 }337 } else {338 lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());339 }340 }341 lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {342 return lib$es6$promise$utils$$isArray(input);343 };344 lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {345 return new Error('Array Methods must be provided an Array');346 };347 lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {348 this._result = new Array(this.length);349 };350 var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;351 lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {352 var enumerator = this;353 var length = enumerator.length;354 var promise = enumerator.promise;355 var input = enumerator._input;356 for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {357 enumerator._eachEntry(input[i], i);358 }359 };360 lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {361 var enumerator = this;362 var c = enumerator._instanceConstructor;363 if (lib$es6$promise$utils$$isMaybeThenable(entry)) {364 if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {365 entry._onerror = null;366 enumerator._settledAt(entry._state, i, entry._result);367 } else {368 enumerator._willSettleAt(c.resolve(entry), i);369 }370 } else {371 enumerator._remaining--;372 enumerator._result[i] = entry;373 }374 };375 lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {376 var enumerator = this;377 var promise = enumerator.promise;378 if (promise._state === lib$es6$promise$$internal$$PENDING) {379 enumerator._remaining--;380 if (state === lib$es6$promise$$internal$$REJECTED) {381 lib$es6$promise$$internal$$reject(promise, value);382 } else {383 enumerator._result[i] = value;384 }385 }386 if (enumerator._remaining === 0) {387 lib$es6$promise$$internal$$fulfill(promise, enumerator._result);388 }389 };390 lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {391 var enumerator = this;392 lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {393 enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);394 }, function(reason) {395 enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);396 });397 };398 function lib$es6$promise$promise$all$$all(entries) {399 return new lib$es6$promise$enumerator$$default(this, entries).promise;400 }401 var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;402 function lib$es6$promise$promise$race$$race(entries) {403 /*jshint validthis:true */404 var Constructor = this;405 var promise = new Constructor(lib$es6$promise$$internal$$noop);406 if (!lib$es6$promise$utils$$isArray(entries)) {407 lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));408 return promise;409 }410 var length = entries.length;411 function onFulfillment(value) {412 lib$es6$promise$$internal$$resolve(promise, value);413 }414 function onRejection(reason) {415 lib$es6$promise$$internal$$reject(promise, reason);416 }417 for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {418 lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);419 }420 return promise;421 }422 var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;423 function lib$es6$promise$promise$resolve$$resolve(object) {424 /*jshint validthis:true */425 var Constructor = this;426 if (object && typeof object === 'object' && object.constructor === Constructor) {427 return object;428 }429 var promise = new Constructor(lib$es6$promise$$internal$$noop);430 lib$es6$promise$$internal$$resolve(promise, object);431 return promise;432 }433 var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;434 function lib$es6$promise$promise$reject$$reject(reason) {435 /*jshint validthis:true */436 var Constructor = this;437 var promise = new Constructor(lib$es6$promise$$internal$$noop);438 lib$es6$promise$$internal$$reject(promise, reason);439 return promise;440 }441 var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;442 var lib$es6$promise$promise$$counter = 0;443 function lib$es6$promise$promise$$needsResolver() {444 throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');445 }446 function lib$es6$promise$promise$$needsNew() {447 throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");448 }449 var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;450 /**451 Promise objects represent the eventual result of an asynchronous operation. The452 primary way of interacting with a promise is through its `then` method, which453 registers callbacks to receive either a promise's eventual value or the reason454 why the promise cannot be fulfilled.455 Terminology456 -----------457 - `promise` is an object or function with a `then` method whose behavior conforms to this specification.458 - `thenable` is an object or function that defines a `then` method.459 - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).460 - `exception` is a value that is thrown using the throw statement.461 - `reason` is a value that indicates why a promise was rejected.462 - `settled` the final resting state of a promise, fulfilled or rejected.463 A promise can be in one of three states: pending, fulfilled, or rejected.464 Promises that are fulfilled have a fulfillment value and are in the fulfilled465 state. Promises that are rejected have a rejection reason and are in the466 rejected state. A fulfillment value is never a thenable.467 Promises can also be said to *resolve* a value. If this value is also a468 promise, then the original promise's settled state will match the value's469 settled state. So a promise that *resolves* a promise that rejects will470 itself reject, and a promise that *resolves* a promise that fulfills will471 itself fulfill.472 Basic Usage:473 ------------474 ```js475 var promise = new Promise(function(resolve, reject) {476 // on success477 resolve(value);478 // on failure479 reject(reason);480 });481 promise.then(function(value) {482 // on fulfillment483 }, function(reason) {484 // on rejection485 });486 ```487 Advanced Usage:488 ---------------489 Promises shine when abstracting away asynchronous interactions such as490 `XMLHttpRequest`s.491 ```js492 function getJSON(url) {493 return new Promise(function(resolve, reject){494 var xhr = new XMLHttpRequest();495 xhr.open('GET', url);496 xhr.onreadystatechange = handler;497 xhr.responseType = 'json';498 xhr.setRequestHeader('Accept', 'application/json');499 xhr.send();500 function handler() {501 if (this.readyState === this.DONE) {502 if (this.status === 200) {503 resolve(this.response);504 } else {505 reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));506 }507 }508 };509 });510 }511 getJSON('/posts.json').then(function(json) {512 // on fulfillment513 }, function(reason) {514 // on rejection515 });516 ```517 Unlike callbacks, promises are great composable primitives.518 ```js519 Promise.all([520 getJSON('/posts'),521 getJSON('/comments')522 ]).then(function(values){523 values[0] // => postsJSON524 values[1] // => commentsJSON525 return values;526 });527 ```528 @class Promise529 @param {function} resolver530 Useful for tooling.531 @constructor532 */533 function lib$es6$promise$promise$$Promise(resolver) {534 this._id = lib$es6$promise$promise$$counter++;535 this._state = undefined;536 this._result = undefined;537 this._subscribers = [];538 if (lib$es6$promise$$internal$$noop !== resolver) {539 if (!lib$es6$promise$utils$$isFunction(resolver)) {540 lib$es6$promise$promise$$needsResolver();541 }542 if (!(this instanceof lib$es6$promise$promise$$Promise)) {543 lib$es6$promise$promise$$needsNew();544 }545 lib$es6$promise$$internal$$initializePromise(this, resolver);546 }547 }548 lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;549 lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;550 lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;551 lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;552 lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;553 lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;554 lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;555 lib$es6$promise$promise$$Promise.prototype = {556 constructor: lib$es6$promise$promise$$Promise,557 /**558 The primary way of interacting with a promise is through its `then` method,559 which registers callbacks to receive either a promise's eventual value or the560 reason why the promise cannot be fulfilled.561 ```js562 findUser().then(function(user){563 // user is available564 }, function(reason){565 // user is unavailable, and you are given the reason why566 });567 ```568 Chaining569 --------570 The return value of `then` is itself a promise. This second, 'downstream'571 promise is resolved with the return value of the first promise's fulfillment572 or rejection handler, or rejected if the handler throws an exception.573 ```js574 findUser().then(function (user) {575 return user.name;576 }, function (reason) {577 return 'default name';578 }).then(function (userName) {579 // If `findUser` fulfilled, `userName` will be the user's name, otherwise it580 // will be `'default name'`581 });582 findUser().then(function (user) {583 throw new Error('Found user, but still unhappy');584 }, function (reason) {585 throw new Error('`findUser` rejected and we're unhappy');586 }).then(function (value) {587 // never reached588 }, function (reason) {589 // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.590 // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.591 });592 ```593 If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.594 ```js595 findUser().then(function (user) {596 throw new PedagogicalException('Upstream error');597 }).then(function (value) {598 // never reached599 }).then(function (value) {600 // never reached601 }, function (reason) {602 // The `PedgagocialException` is propagated all the way down to here603 });604 ```605 Assimilation606 ------------607 Sometimes the value you want to propagate to a downstream promise can only be608 retrieved asynchronously. This can be achieved by returning a promise in the609 fulfillment or rejection handler. The downstream promise will then be pending610 until the returned promise is settled. This is called *assimilation*.611 ```js612 findUser().then(function (user) {613 return findCommentsByAuthor(user);614 }).then(function (comments) {615 // The user's comments are now available616 });617 ```618 If the assimliated promise rejects, then the downstream promise will also reject.619 ```js620 findUser().then(function (user) {621 return findCommentsByAuthor(user);622 }).then(function (comments) {623 // If `findCommentsByAuthor` fulfills, we'll have the value here624 }, function (reason) {625 // If `findCommentsByAuthor` rejects, we'll have the reason here626 });627 ```628 Simple Example629 --------------630 Synchronous Example631 ```javascript632 var result;633 try {634 result = findResult();635 // success636 } catch(reason) {637 // failure638 }639 ```640 Errback Example641 ```js642 findResult(function(result, err){643 if (err) {644 // failure645 } else {646 // success647 }648 });649 ```650 Promise Example;651 ```javascript652 findResult().then(function(result){653 // success654 }, function(reason){655 // failure656 });657 ```658 Advanced Example659 --------------660 Synchronous Example661 ```javascript662 var author, books;663 try {664 author = findAuthor();665 books = findBooksByAuthor(author);666 // success667 } catch(reason) {668 // failure669 }670 ```671 Errback Example672 ```js673 function foundBooks(books) {674 }675 function failure(reason) {676 }677 findAuthor(function(author, err){678 if (err) {679 failure(err);680 // failure681 } else {682 try {683 findBoooksByAuthor(author, function(books, err) {684 if (err) {685 failure(err);686 } else {687 try {688 foundBooks(books);689 } catch(reason) {690 failure(reason);691 }692 }693 });694 } catch(error) {695 failure(err);696 }697 // success698 }699 });700 ```701 Promise Example;702 ```javascript703 findAuthor().704 then(findBooksByAuthor).705 then(function(books){706 // found books707 }).catch(function(reason){708 // something went wrong709 });710 ```711 @method then712 @param {Function} onFulfilled713 @param {Function} onRejected714 Useful for tooling.715 @return {Promise}716 */717 then: function(onFulfillment, onRejection) {718 var parent = this;719 var state = parent._state;720 if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {721 return this;722 }723 var child = new this.constructor(lib$es6$promise$$internal$$noop);724 var result = parent._result;725 if (state) {726 var callback = arguments[state - 1];727 lib$es6$promise$asap$$asap(function(){728 lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);729 });730 } else {731 lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);732 }733 return child;734 },735 /**736 `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same737 as the catch block of a try/catch statement.738 ```js739 function findAuthor(){740 throw new Error('couldn't find that author');741 }...
es6-promise-modified.js
Source:es6-promise-modified.js
...37 var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;38 var lib$es6$promise$asap$$len = 0;39 var lib$es6$promise$asap$$vertxNext;40 var lib$es6$promise$asap$$customSchedulerFn;41 var lib$es6$promise$asap$$asap = function asap(callback, arg) {42 lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;43 lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;44 lib$es6$promise$asap$$len += 2;45 if (lib$es6$promise$asap$$len === 2) {46 // If len is 2, that means that we need to schedule an async flush.47 // If additional callbacks are queued before the queue is flushed, they48 // will be processed by this flush that we are scheduling.49 if (lib$es6$promise$asap$$customSchedulerFn) {50 lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);51 } else {52 lib$es6$promise$asap$$scheduleFlush();53 }54 }55 }56 function lib$es6$promise$asap$$setScheduler(scheduleFn) {57 lib$es6$promise$asap$$customSchedulerFn = scheduleFn;58 }59 function lib$es6$promise$asap$$setAsap(asapFn) {60 lib$es6$promise$asap$$asap = asapFn;61 }62 var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;63 var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};64 var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;65 var lib$es6$promise$asap$$isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';66 // test for web worker but not in IE1067 var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&68 typeof importScripts !== 'undefined' &&69 typeof MessageChannel !== 'undefined';70 // node71 function lib$es6$promise$asap$$useNextTick() {72 // node version 0.10.x displays a deprecation warning when nextTick is used recursively73 // see https://github.com/cujojs/when/issues/410 for details74 return function() {75 process.nextTick(lib$es6$promise$asap$$flush);76 };77 }78 // vertx79 function lib$es6$promise$asap$$useVertxTimer() {80 return function() {81 lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);82 };83 }84 function lib$es6$promise$asap$$useMutationObserver() {85 var iterations = 0;86 var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);87 var node = document.createTextNode('');88 observer.observe(node, { characterData: true });89 return function() {90 node.data = (iterations = ++iterations % 2);91 };92 }93 // web worker94 function lib$es6$promise$asap$$useMessageChannel() {95 var channel = new MessageChannel();96 channel.port1.onmessage = lib$es6$promise$asap$$flush;97 return function () {98 channel.port2.postMessage(0);99 };100 }101 function lib$es6$promise$asap$$useSetTimeout() {102 return function() {103 setTimeout(lib$es6$promise$asap$$flush, 1);104 };105 }106 var lib$es6$promise$asap$$queue = new Array(1000);107 function lib$es6$promise$asap$$flush() {108 for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {109 var callback = lib$es6$promise$asap$$queue[i];110 var arg = lib$es6$promise$asap$$queue[i+1];111 callback(arg);112 lib$es6$promise$asap$$queue[i] = undefined;113 lib$es6$promise$asap$$queue[i+1] = undefined;114 }115 lib$es6$promise$asap$$len = 0;116 }117 function lib$es6$promise$asap$$attemptVertx() {118 try {119 var r = require;120 var vertx = r('vertx');121 lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;122 return lib$es6$promise$asap$$useVertxTimer();123 } catch(e) {124 return lib$es6$promise$asap$$useSetTimeout();125 }126 }127 var lib$es6$promise$asap$$scheduleFlush;128 // Decide what async method to use to triggering processing of queued callbacks:129 if (lib$es6$promise$asap$$isNode) {130 lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();131 } else if (lib$es6$promise$asap$$BrowserMutationObserver) {132 lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();133 } else if (lib$es6$promise$asap$$isWorker) {134 lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();135 } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {136 lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();137 } else {138 lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();139 }140 function lib$es6$promise$then$$then(onFulfillment, onRejection) {141 var parent = this;142 var child = new this.constructor(lib$es6$promise$$internal$$noop);143 if (child[lib$es6$promise$$internal$$PROMISE_ID] === undefined) {144 lib$es6$promise$$internal$$makePromise(child);145 }146 var state = parent._state;147 if (state) {148 var callback = arguments[state - 1];149 lib$es6$promise$asap$$asap(function(){150 lib$es6$promise$$internal$$invokeCallback(state, child, callback, parent._result);151 });152 } else {153 lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);154 }155 return child;156 }157 var lib$es6$promise$then$$default = lib$es6$promise$then$$then;158 function lib$es6$promise$promise$resolve$$resolve(object) {159 /*jshint validthis:true */160 var Constructor = this;161 if (object && typeof object === 'object' && object.constructor === Constructor) {162 return object;163 }164 var promise = new Constructor(lib$es6$promise$$internal$$noop);165 lib$es6$promise$$internal$$resolve(promise, object);166 return promise;167 }168 var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;169 var lib$es6$promise$$internal$$PROMISE_ID = Math.random().toString(36).substring(16);170 function lib$es6$promise$$internal$$noop() {}171 var lib$es6$promise$$internal$$PENDING = void 0;172 var lib$es6$promise$$internal$$FULFILLED = 1;173 var lib$es6$promise$$internal$$REJECTED = 2;174 var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();175 function lib$es6$promise$$internal$$selfFulfillment() {176 return new TypeError("You cannot resolve a promise with itself");177 }178 function lib$es6$promise$$internal$$cannotReturnOwn() {179 return new TypeError('A promises callback cannot return that same promise.');180 }181 function lib$es6$promise$$internal$$getThen(promise) {182 try {183 return promise.then;184 } catch(error) {185 lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;186 return lib$es6$promise$$internal$$GET_THEN_ERROR;187 }188 }189 function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {190 try {191 then.call(value, fulfillmentHandler, rejectionHandler);192 } catch(e) {193 return e;194 }195 }196 function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {197 lib$es6$promise$asap$$asap(function(promise) {198 var sealed = false;199 var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {200 if (sealed) { return; }201 sealed = true;202 if (thenable !== value) {203 lib$es6$promise$$internal$$resolve(promise, value);204 } else {205 lib$es6$promise$$internal$$fulfill(promise, value);206 }207 }, function(reason) {208 if (sealed) { return; }209 sealed = true;210 lib$es6$promise$$internal$$reject(promise, reason);211 }, 'Settle: ' + (promise._label || ' unknown promise'));212 if (!sealed && error) {213 sealed = true;214 lib$es6$promise$$internal$$reject(promise, error);215 }216 }, promise);217 }218 function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {219 if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {220 lib$es6$promise$$internal$$fulfill(promise, thenable._result);221 } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {222 lib$es6$promise$$internal$$reject(promise, thenable._result);223 } else {224 lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {225 lib$es6$promise$$internal$$resolve(promise, value);226 }, function(reason) {227 lib$es6$promise$$internal$$reject(promise, reason);228 });229 }230 }231 function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable, then) {232 if (maybeThenable.constructor === promise.constructor &&233 then === lib$es6$promise$then$$default &&234 constructor.resolve === lib$es6$promise$promise$resolve$$default) {235 lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);236 } else {237 if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {238 lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);239 } else if (then === undefined) {240 lib$es6$promise$$internal$$fulfill(promise, maybeThenable);241 } else if (lib$es6$promise$utils$$isFunction(then)) {242 lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);243 } else {244 lib$es6$promise$$internal$$fulfill(promise, maybeThenable);245 }246 }247 }248 function lib$es6$promise$$internal$$resolve(promise, value) {249 if (promise === value) {250 lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());251 } else if (lib$es6$promise$utils$$objectOrFunction(value)) {252 lib$es6$promise$$internal$$handleMaybeThenable(promise, value, lib$es6$promise$$internal$$getThen(value));253 } else {254 lib$es6$promise$$internal$$fulfill(promise, value);255 }256 }257 function lib$es6$promise$$internal$$publishRejection(promise) {258 if (promise._onerror) {259 promise._onerror(promise._result);260 }261 lib$es6$promise$$internal$$publish(promise);262 }263 function lib$es6$promise$$internal$$fulfill(promise, value) {264 if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }265 promise._result = value;266 promise._state = lib$es6$promise$$internal$$FULFILLED;267 if (promise._subscribers.length !== 0) {268 lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);269 }270 }271 function lib$es6$promise$$internal$$reject(promise, reason) {272 if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }273 promise._state = lib$es6$promise$$internal$$REJECTED;274 promise._result = reason;275 lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);276 }277 function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {278 var subscribers = parent._subscribers;279 var length = subscribers.length;280 parent._onerror = null;281 subscribers[length] = child;282 subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;283 subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;284 if (length === 0 && parent._state) {285 lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);286 }287 }288 function lib$es6$promise$$internal$$publish(promise) {289 var subscribers = promise._subscribers;290 var settled = promise._state;291 if (subscribers.length === 0) { return; }292 var child, callback, detail = promise._result;293 for (var i = 0; i < subscribers.length; i += 3) {294 child = subscribers[i];295 callback = subscribers[i + settled];296 if (child) {297 lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);298 } else {299 callback(detail);...
fetchManager.spec.js
Source:fetchManager.spec.js
1import {strict as assert} from 'assert';2import {readdirSync} from 'fs';3import path from 'path';4import {isKeyValue, jsonBufferToAny} from '@svizzle/utils';5import * as _ from 'lamb';6import {filter} from 'rxjs/operators';7import {fetch} from 'undici';8import {makeWebStreamsFetcher} from '../webstreams';9import {createFetchManagerStreams} from './fetchManager';10import {11 getFileNamesMap,12 getKeysNamed,13 loadJsons,14 makeUriMap,15 startServer,16} from './specUtils';17// TODO verify we catch all potential exceptions18// test environment19const baseServerPath = path.resolve('../atlas/data/dist/NUTS/topojson');20const TIMEOUT = 20000;21const PORT = 4000;22const fileNamesMap = getFileNamesMap(readdirSync(baseServerPath));23const uriMap = makeUriMap(`http://localhost:${PORT}/`)(fileNamesMap);24const allKeys = _.keys(uriMap);25const keysFrom2021 = getKeysNamed('2021')(allKeys);26const keysFrom2016 = getKeysNamed('2016')(allKeys);27const keysFrom2013 = getKeysNamed('2013')(allKeys);28describe('fetchManager', function () {29 // eslint-disable-next-line no-invalid-this30 this.timeout(TIMEOUT);31 const server = startServer({32 port: PORT,33 basePath: baseServerPath34 });35 after(function () {36 server.close()37 });38 describe('`_uriMap` property', function () {39 it('the content of the downloaded files should be the same as served resources', function () {40 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny);41 const {42 _asapKeys,43 _outData,44 _outEvents,45 _uriMap46 } = createFetchManagerStreams(downloadFn);47 _uriMap.next(uriMap);48 _asapKeys.next(allKeys);49 return new Promise((resolve, reject) => {50 _outEvents.pipe(51 filter(event => event.type === 'done')52 ).subscribe(async () => {53 const data = _outData.getValue();54 try {55 const expectedJsons = await loadJsons(baseServerPath, allKeys, fileNamesMap);56 assert.deepStrictEqual(data, expectedJsons);57 } catch (e) {58 reject(e);59 }60 resolve();61 })62 })63 });64 describe('change while in progress: should clear the cache and restart downloading', function () {65 it('!= keys, != URIs', function () {66 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny);67 const {68 _asapKeys,69 _outData,70 _outEvents,71 _shouldPrefetch,72 _uriMap73 } = createFetchManagerStreams(downloadFn);74 _shouldPrefetch.next(true);75 _uriMap.next(_.pickIn(uriMap, keysFrom2021));76 _asapKeys.next(keysFrom2021);77 return new Promise((resolve, reject) => {78 let switchedMap;79 let totalCompleted = 0;80 _outEvents.pipe(81 filter(isKeyValue(['type', 'file:complete']))82 ).subscribe(() => {83 totalCompleted++84 // switch after downloading more than half85 if (!switchedMap && totalCompleted > keysFrom2021.length / 2) {86 _uriMap.next(_.pickIn(uriMap, keysFrom2016));87 _asapKeys.next(keysFrom2016);88 switchedMap = true;89 }90 });91 _outEvents.pipe(92 filter(isKeyValue(['type','done']))93 ).subscribe(() => {94 const actualKeys = _.keys(_outData.getValue());95 try {96 assert.deepStrictEqual(97 actualKeys.sort(),98 keysFrom2016.sort()99 );100 } catch (e) {101 reject(e);102 }103 resolve();104 })105 })106 })107 it('= keys, != URIs', function () {108 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny);109 const {110 _asapKeys,111 _outData,112 _outEvents,113 _shouldPrefetch,114 _uriMap115 } = createFetchManagerStreams(downloadFn);116 _shouldPrefetch.next(true);117 _uriMap.next(_.pickIn(uriMap, keysFrom2021));118 _asapKeys.next(keysFrom2021);119 return new Promise((resolve, reject) => {120 let switchedMap;121 let totalCompleted = 0;122 _outEvents.pipe(123 filter(isKeyValue(['type', 'file:complete']))124 ).subscribe(() => {125 totalCompleted++;126 // switch after downloading more than half127 if (!switchedMap && totalCompleted > keysFrom2021.length / 2) {128 const newMap = _.pipe([129 _.pick(keysFrom2016),130 _.pairs,131 _.mapWith(([key, uri]) => [132 key.replace('2016', '2021'),133 uri134 ]),135 _.fromPairs136 ])(uriMap);137 _uriMap.next(newMap);138 switchedMap = true;139 }140 });141 _outEvents.pipe(142 filter(isKeyValue(['type','done']))143 ).subscribe(() => {144 const actualKeys = _.keys(_outData.getValue())145 try {146 assert.deepStrictEqual(147 actualKeys.sort(),148 keysFrom2021.sort()149 );150 } catch (e) {151 reject(e);152 }153 resolve();154 });155 });156 });157 it('!= keys, = URIs', function () {158 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny);159 const {160 _asapKeys,161 _outData,162 _outEvents,163 _shouldPrefetch,164 _uriMap165 } = createFetchManagerStreams(downloadFn);166 _shouldPrefetch.next(true);167 _uriMap.next(_.pickIn(uriMap, keysFrom2021));168 _asapKeys.next(keysFrom2021);169 return new Promise((resolve, reject) => {170 let switchedMap;171 let totalCompleted = 0;172 _outEvents.pipe(173 filter(isKeyValue(['type', 'file:complete']))174 ).subscribe(() => {175 totalCompleted++176 // switch after downloading more than half177 if (!switchedMap && totalCompleted > keysFrom2021.length / 2) {178 const newMap = _.pipe([179 _.pick(keysFrom2021),180 _.pairs,181 _.mapWith(([key, uri]) => [182 key.replace('2021', '2016'),183 uri184 ]),185 _.fromPairs186 ])(uriMap);187 _uriMap.next(newMap);188 _asapKeys.next(keysFrom2016);189 switchedMap = true;190 }191 });192 _outEvents.pipe(193 filter(isKeyValue(['type','done']))194 ).subscribe(() => {195 const actualKeys = _.keys(_outData.getValue());196 try {197 assert.deepStrictEqual(198 actualKeys.sort(),199 keysFrom2016.sort()200 );201 } catch (e) {202 reject(e);203 }204 resolve();205 })206 });207 });208 });209 });210 describe('`_shouldPrefetch` property', function () {211 it('false: it should only load files in `asapKeys`', function () {212 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny);213 const {214 _asapKeys,215 _nextKeys,216 _outData,217 _outEvents,218 _shouldPrefetch,219 _uriMap220 } = createFetchManagerStreams(downloadFn);221 _shouldPrefetch.next(false); // keep? it's the default value222 _uriMap.next(uriMap);223 _asapKeys.next(keysFrom2021);224 _nextKeys.next(keysFrom2016);225 return new Promise((resolve, reject) => {226 _outEvents.pipe(227 filter(event => event.type === 'done')228 ).subscribe(() => {229 const data = _outData.getValue();230 const keys = _.keys(data);231 try {232 assert.deepStrictEqual(233 keys.sort(),234 keysFrom2021.sort()235 );236 } catch (e) {237 reject(e);238 }239 resolve();240 });241 });242 });243 it('true: it should load all files', function () {244 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny);245 const {246 _asapKeys,247 _nextKeys,248 _outData,249 _outEvents,250 _shouldPrefetch,251 _uriMap252 } = createFetchManagerStreams(downloadFn);253 _shouldPrefetch.next(true);254 _uriMap.next(uriMap);255 _asapKeys.next(keysFrom2021);256 _nextKeys.next(keysFrom2016);257 return new Promise((resolve, reject) => {258 _outEvents.pipe(259 filter(event => event.type === 'done')260 ).subscribe(() => {261 const data = _outData.getValue();262 const keys = _.keys(data);263 try {264 assert.deepStrictEqual(265 keys.sort(),266 _.keys(uriMap).sort()267 );268 } catch (e) {269 reject(e);270 }271 resolve();272 });273 });274 });275 describe('change while in progress', function () {276 it('true -> false while asap in progress: should complete and stop', function () {277 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny);278 const {279 _asapKeys,280 _nextKeys,281 _outData,282 _outEvents,283 _shouldPrefetch,284 _uriMap285 } = createFetchManagerStreams(downloadFn);286 _shouldPrefetch.next(true);287 _uriMap.next(uriMap);288 _asapKeys.next(keysFrom2021);289 _nextKeys.next(keysFrom2016);290 return new Promise((resolve, reject) => {291 let turnedItOff292 _outEvents.pipe(293 filter(isKeyValue(['type', 'file:complete']))294 ).subscribe(() => {295 if (!turnedItOff) {296 _shouldPrefetch.next(false);297 turnedItOff = true;298 }299 });300 _outEvents.pipe(301 filter(isKeyValue(['type', 'done']))302 ).subscribe(() => {303 const data = _outData.getValue();304 const keys = _.keys(data);305 try {306 assert.deepStrictEqual(307 keys.sort(),308 keysFrom2021.sort()309 );310 } catch (e) {311 reject(e);312 }313 resolve();314 });315 });316 });317 it('true -> false after asap: should stop', function () {318 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny)319 const {320 _asapKeys,321 _nextKeys,322 _outData,323 _outEvents,324 _shouldPrefetch,325 _uriMap326 } = createFetchManagerStreams(downloadFn);327 _shouldPrefetch.next(true);328 _uriMap.next(uriMap);329 _asapKeys.next(keysFrom2021);330 _nextKeys.next(keysFrom2016);331 return new Promise((resolve, reject) => {332 let hasNextStarted;333 let turnedItOff;334 _outEvents.pipe(335 filter(isKeyValue(['type', 'group:complete']))336 ).subscribe(() => {337 if (!hasNextStarted) {338 hasNextStarted = true;339 }340 });341 _outEvents.pipe(342 filter(isKeyValue(['type', 'file:complete']))343 ).subscribe(() => {344 if (hasNextStarted && !turnedItOff) {345 _shouldPrefetch.next(false);346 turnedItOff = true;347 }348 });349 _outEvents.pipe(350 filter(isKeyValue(['type', 'done']))351 ).subscribe(() => {352 const data = _outData.getValue();353 const keys = _.keys(data);354 try {355 assert(356 _.is(357 _.intersection(keys, keysFrom2021).length,358 keysFrom2021.length359 )360 );361 } catch (e) {362 reject(e);363 }364 resolve();365 });366 });367 });368 it('false -> true while asap in progress: should continue', function () {369 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny);370 const {371 _asapKeys,372 _nextKeys,373 _outData,374 _outEvents,375 _shouldPrefetch,376 _uriMap377 } = createFetchManagerStreams(downloadFn);378 _shouldPrefetch.next(false);379 _uriMap.next(uriMap);380 _asapKeys.next(keysFrom2021);381 _nextKeys.next(keysFrom2016);382 return new Promise((resolve, reject) => {383 let turnedItOn;384 _outEvents.pipe(385 // tap(console.log),386 filter(isKeyValue(['type', 'file:complete']))387 ).subscribe(() => {388 if (!turnedItOn) {389 _shouldPrefetch.next(true);390 turnedItOn = true;391 }392 });393 _outEvents.pipe(394 filter(isKeyValue(['type', 'done']))395 ).subscribe(() => {396 const data = _outData.getValue();397 const keys = _.keys(data);398 try {399 assert.deepStrictEqual(400 keys.sort(),401 allKeys.sort()402 );403 } catch (e) {404 reject(e);405 }406 resolve();407 });408 });409 });410 it('false -> true after asap: should restart, skipping asap and download everything else', function () {411 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny);412 const {413 _asapKeys,414 _nextKeys,415 _outData,416 _outEvents,417 _shouldPrefetch,418 _uriMap419 } = createFetchManagerStreams(downloadFn);420 _shouldPrefetch.next(false);421 _uriMap.next(uriMap);422 _asapKeys.next(keysFrom2021);423 _nextKeys.next(keysFrom2016);424 return new Promise((resolve, reject) => {425 let turnedItOn;426 _outEvents.pipe(427 // tap(console.log),428 filter(isKeyValue(['type', 'done']))429 ).subscribe(() => {430 if (!turnedItOn) {431 turnedItOn = true;432 _shouldPrefetch.next(true);433 } else {434 const data = _outData.getValue();435 const keys = _.keys(data);436 try {437 assert(438 _.is(439 _.intersection(keys, keysFrom2021).length,440 keysFrom2021.length441 )442 );443 } catch (e) {444 reject(e);445 }446 resolve();447 }448 });449 });450 });451 });452 });453 describe('priority properties (`_asapKeys` and `_nextKeys`)', function () {454 const asapKeys = keysFrom2021;455 const nextKeys = keysFrom2016;456 const restKeys = _.difference(457 allKeys,458 [...asapKeys, ...nextKeys]459 );460 describe('static', function () {461 it('should load all files in correct order (`_asapKeys` then `_nextKeys` then `_restKeys`)', function () {462 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny);463 const {464 _asapKeys,465 _nextKeys,466 _outEvents,467 _shouldPrefetch,468 _uriMap469 } = createFetchManagerStreams(downloadFn);470 _shouldPrefetch.next(true);471 _uriMap.next(uriMap);472 _asapKeys.next(asapKeys);473 _nextKeys.next(nextKeys);474 return new Promise(resolve => {475 let groups = [];476 let activeGroup;477 let keysForGroup = {}478 _outEvents.pipe(479 // filter(event => event.type === 'groupStart'),480 filter(isKeyValue(['type','group:start']))481 // filter(_.hasKeyValue('type','groupStart')) // TODO TBD deprecation482 ).subscribe(({groupId}) => {483 groups.push(groupId);484 activeGroup = groupId;485 keysForGroup[activeGroup] = [];486 });487 _outEvents.pipe(488 filter(event => event.type === 'file:complete')489 ).subscribe(({key}) => {490 keysForGroup[activeGroup].push(key);491 });492 _outEvents.pipe(493 filter(event => event.type === 'done')494 ).subscribe(() => {495 assert.deepStrictEqual(496 groups,497 ['asap', 'next', 'rest'],498 'Groups loaded out of order'499 );500 assert.deepStrictEqual(501 keysForGroup.asap.sort(),502 asapKeys.sort(),503 'Asap not equal'504 );505 assert.deepStrictEqual(506 keysForGroup.next.sort(),507 nextKeys.sort(),508 'Next not equal'509 );510 assert.deepStrictEqual(511 keysForGroup.rest.sort(),512 restKeys.sort(),513 'Rest not equal'514 );515 resolve();516 });517 });518 });519 });520 describe('caching', function () {521 it(`should not redownload cached files`, function () {522 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny);523 const {524 _asapKeys,525 _outEvents,526 _shouldPrefetch,527 _uriMap528 } = createFetchManagerStreams(downloadFn);529 _shouldPrefetch.next(true);530 _uriMap.next(uriMap);531 _asapKeys.next(asapKeys);532 return new Promise((resolve, reject) => {533 _outEvents.pipe(534 filter(event => event.type === 'group:complete'),535 filter(event => event.groupId === 'next')536 ).subscribe(({keys}) => {537 try {538 assert(keys.length === 0, 'No keys should be requested on \'next\' group');539 } catch (e) {540 reject(e);541 }542 });543 _outEvents.pipe(544 filter(event => event.type === 'done')545 ).subscribe(() => {546 resolve();547 });548 });549 });550 });551 describe('priority change', function () {552 it('while downloading `_asapKeys` those remaining in `_asapKeys` should continue downloading', function () {553 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny);554 const {555 _asapKeys,556 _nextKeys,557 _outEvents,558 _shouldPrefetch,559 _uriMap560 } = createFetchManagerStreams(downloadFn);561 _shouldPrefetch.next(true);562 _uriMap.next(uriMap);563 _asapKeys.next(asapKeys);564 _nextKeys.next(nextKeys);565 return new Promise((resolve, reject) => {566 let newAsap;567 _outEvents.pipe(568 // tap(console.log),569 filter(event => event.type === 'file:complete')570 ).subscribe(({key}) => {571 if (!newAsap) {572 newAsap = _.difference(573 asapKeys,574 [key]575 );576 _asapKeys.next(newAsap);577 }578 });579 _outEvents.pipe(580 filter(event => event.type === 'file:cancel')581 ).subscribe(({key}) => {582 try {583 assert(!_.isIn(asapKeys, key));584 } catch (e) {585 reject(e);586 }587 });588 _outEvents.pipe(589 filter(event => event.type === 'done')590 ).subscribe(() => {591 resolve();592 });593 });594 });595 it('while downloading `_asapKeys` those not remaining in `_asapKeys` should be cancelled', function () {596 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny);597 const {598 _asapKeys,599 _nextKeys,600 _outEvents,601 _shouldPrefetch,602 _uriMap603 } = createFetchManagerStreams(downloadFn);604 _shouldPrefetch.next(true);605 _uriMap.next(uriMap);606 _asapKeys.next(asapKeys);607 _nextKeys.next(nextKeys);608 return new Promise((resolve, reject) => {609 let newAsap;610 const filesCompleted = [];611 let actualCancelledKeys = [];612 _outEvents.pipe(613 filter(event => event.type === 'file:complete')614 ).subscribe(({key}) => {615 filesCompleted.push(key);616 if (!newAsap) {617 newAsap = nextKeys;618 // Swapping keys to trigger restart619 _asapKeys.next(newAsap);620 _nextKeys.next(asapKeys);621 }622 });623 _outEvents.pipe(624 filter(({type}) => type === 'group:complete'),625 filter(({groupId}) => groupId === 'asap')626 ).subscribe(({cancelledKeys}) => {627 actualCancelledKeys = cancelledKeys;628 });629 _outEvents.pipe(630 filter(event => event.type === 'done')631 ).subscribe(() => {632 const expectedCancelledFiles = _.difference(633 asapKeys,634 filesCompleted635 );636 try {637 assert.deepStrictEqual(638 actualCancelledKeys.sort(),639 expectedCancelledFiles.sort()640 );641 resolve();642 } catch (e) {643 reject(e);644 }645 });646 });647 });648 it('while downloading `_nextKeys` those moving to `_asapKeys` should continue downloading', function () {649 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny);650 const {651 _asapKeys,652 _nextKeys,653 _outEvents,654 _shouldPrefetch,655 _uriMap656 } = createFetchManagerStreams(downloadFn);657 _shouldPrefetch.next(true);658 _uriMap.next(uriMap);659 _asapKeys.next(asapKeys);660 _nextKeys.next(nextKeys);661 return new Promise((resolve, reject) => {662 let nextStarted = false;663 let newAsap;664 _outEvents.pipe(665 filter(({type}) => type === 'group:start'),666 filter(({groupId}) => groupId === 'next')667 ).subscribe(() => {668 nextStarted = true;669 })670 _outEvents.pipe(671 filter(event => event.type === 'file:complete')672 ).subscribe(({key}) => {673 if (nextStarted && !newAsap) {674 newAsap = _.difference(675 nextKeys,676 [key]677 );678 _asapKeys.next(newAsap);679 _nextKeys.next(asapKeys);680 }681 });682 _outEvents.pipe(683 filter(event => event.type === 'file:cancel')684 ).subscribe(({key}) => {685 try {686 assert(!_.isIn(newAsap, key));687 } catch (e) {688 reject(e);689 }690 });691 _outEvents.pipe(692 filter(event => event.type === 'done')693 ).subscribe(() => {694 resolve();695 });696 });697 });698 it('while downloading `_nextKeys` those not moving to `_asapKeys` should be cancelled', function () {699 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny);700 const {701 _asapKeys,702 _nextKeys,703 _outEvents,704 _shouldPrefetch,705 _uriMap706 } = createFetchManagerStreams(downloadFn);707 _shouldPrefetch.next(true);708 _uriMap.next(uriMap);709 _asapKeys.next(asapKeys);710 _nextKeys.next(nextKeys);711 return new Promise((resolve, reject) => {712 let nextStarted = false;713 let newAsap;714 const filesCompleted = [];715 let actualCancelledKeys = [];716 _outEvents.pipe(717 filter(({type}) => type === 'group:start'),718 filter(({groupId}) => groupId === 'next')719 ).subscribe(() => {720 nextStarted = true;721 });722 _outEvents.pipe(723 filter(event => event.type === 'file:complete')724 ).subscribe(({key}) => {725 filesCompleted.push(key);726 if (nextStarted && !newAsap) {727 newAsap = keysFrom2013;728 _asapKeys.next(newAsap);729 }730 });731 _outEvents.pipe(732 filter(({type}) => type === 'group:complete'),733 filter(({groupId}) => groupId === 'next')734 ).subscribe(({cancelledKeys}) => {735 actualCancelledKeys = cancelledKeys;736 });737 _outEvents.pipe(738 filter(event => event.type === 'done')739 ).subscribe(() => {740 const expectedCancelledFiles = _.difference(741 nextKeys,742 filesCompleted743 );744 try {745 assert.deepStrictEqual(746 actualCancelledKeys.sort(),747 expectedCancelledFiles.sort()748 );749 resolve();750 } catch (e) {751 reject(e);752 }753 });754 });755 });756 it('while downloading `_restKeys` those moving to `_asapKeys` should continue downloading', function () {757 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny)758 const {759 _asapKeys,760 _nextKeys,761 _outEvents,762 _shouldPrefetch,763 _uriMap764 } = createFetchManagerStreams(downloadFn);765 _shouldPrefetch.next(true);766 _uriMap.next(uriMap);767 _asapKeys.next(asapKeys);768 _nextKeys.next(nextKeys);769 return new Promise((resolve, reject) => {770 let nextStarted = false;771 let newAsap;772 _outEvents.pipe(773 // tap(console.log),774 filter(({type}) => type === 'group:start'),775 filter(({groupId}) => groupId === 'rest')776 ).subscribe(() => {777 nextStarted = true;778 })779 _outEvents.pipe(780 filter(event => event.type === 'file:complete')781 ).subscribe(({key}) => {782 if (nextStarted && !newAsap) {783 newAsap = _.difference(784 restKeys,785 [key]786 );787 _asapKeys.next(newAsap);788 }789 });790 _outEvents.pipe(791 filter(event => event.type === 'file:cancel')792 ).subscribe(({key}) => {793 try {794 assert(!_.isIn(newAsap, key));795 } catch (e) {796 reject(e);797 }798 })799 _outEvents.pipe(800 filter(event => event.type === 'done')801 ).subscribe(() => {802 resolve();803 });804 });805 });806 it('while downloading `_restKeys` those not moving to `_asapKeys` should be cancelled', function () {807 const downloadFn = makeWebStreamsFetcher(fetch, jsonBufferToAny);808 const {809 _asapKeys,810 _nextKeys,811 _outEvents,812 _shouldPrefetch,813 _uriMap814 } = createFetchManagerStreams(downloadFn);815 _shouldPrefetch.next(true);816 _uriMap.next(uriMap);817 _asapKeys.next(asapKeys);818 _nextKeys.next(nextKeys);819 return new Promise((resolve, reject) => {820 let restStarted = false;821 let newAsap;822 let actualCancelledKeys;823 const filesCompleted = [];824 _outEvents.pipe(825 filter(({type}) => type === 'group:start'),826 filter(({groupId}) => groupId === 'rest')827 ).subscribe(() => {828 restStarted = true;829 })830 _outEvents.pipe(831 filter(event => event.type === 'file:complete')832 ).subscribe(({key}) => {833 filesCompleted.push(key);834 if (restStarted && !newAsap) {835 newAsap = keysFrom2016;836 _asapKeys.next(newAsap);837 _nextKeys.next(keysFrom2013);838 }839 });840 _outEvents.pipe(841 filter(({type}) => type === 'group:complete'),842 filter(({groupId}) => groupId === 'rest')843 ).subscribe(({cancelledKeys}) => {844 actualCancelledKeys = cancelledKeys;845 });846 _outEvents.pipe(847 filter(event => event.type === 'done')848 ).subscribe(() => {849 const expectedCancelledFiles = _.difference(850 restKeys,851 filesCompleted852 );853 try {854 assert.deepStrictEqual(855 actualCancelledKeys.sort(),856 expectedCancelledFiles.sort()857 );858 resolve();859 } catch (e) {860 reject(e);861 }862 });863 });864 });865 });866 });...
admin-script.js
Source:admin-script.js
1(function ($) {2 $(function () {3 $('.asap-tab').click(function(){4 var attr_id = $(this).attr('id');5 var id = attr_id.replace('asap-tab-','');6 $('.asap-tab').removeClass('asap-active-tab');7 $(this).addClass('asap-active-tab'); 8 $('.asap-section').hide();9 $('#asap-section-'+id).show();10 });11 12 13 14 $('#asap-fb-authorize-ref').click(function(){15 $('input[name="asap_fb_authorize"]').click(); 16 });1718 $('.asfap-apitype').change(function(){19 if (this.value === 'graph_api') {20 $('.apfap-graph-api-options').show();21 $('.apfap-android-api-options').hide();22 }23 else if (this.value === 'mobile_api') {24 $('.apfap-graph-api-options').hide();25 $('.apfap-android-api-options').show();26 }2728 });2930 var apitype = $(".asfap-apitype:checked").val();31 if (apitype === 'graph_api') {32 $('.apfap-graph-api-options').show();33 $('.apfap-android-api-options').hide();34 }35 else if (apitype === 'mobile_api') {36 $('.apfap-graph-api-options').hide();37 $('.apfap-android-api-options').show();38 }3940 /*41 * Get Access Token42 */43 $('.asap-network-inner-wrap').on('click','.asap-generate-token-btn',function (e) {44 e.preventDefault();45 var fb_email = $('.asap-fb-emailid').val();46 var fb_password = $('.asap-fb-pass').val();47 $.ajax({48 type: 'post',49 url: asfap_backend_js_obj.ajax_url,50 data: {51 fb_email: fb_email,52 fb_password: fb_password,53 action: 'asfap_access_token_ajax_action',54 _wpnonce: asfap_backend_js_obj.ajax_nonce55 },56 beforeSend: function() {57 $('.asap-ajax-loader1').css('visibility','visible');58 $('.asap-ajax-loader1').css('opacity',1);59 },60 success: function (res) {61 if( res.type == 'success' ){62 $('.asap-generated-atwrapper').slideDown('slow');63 $('.asap-generated-access-token-wrapper').html('<iframe src="'+res.message+'" frameborder="1" scrolling="yes" id="fbFrame"></iframe>'); 64 65 }66 else{67 $('.asap-generated-atwrapper').hide();68 $('.asap-generated-access-token-wrapper').html(res.message).css({color:'red'});69 }70 $('.asap-ajax-loader1').css('visibility','hidden');71 $('.asap-ajax-loader1').css('opacity',0);72 }73 });74 });7576 var dropdown = $('#asap-button-template-floating');77 $('.asap-network-inner-wrap').on('click','.asap-add-account-button',function (e) {78 e.preventDefault();79 var token_url = $('#asap-generated-access-url').val();80 $.ajax({81 type: 'post',82 url: asfap_backend_js_obj.ajax_url,83 data: {84 token_url: token_url,85 action: 'asfap_add_account_action',86 _wpnonce: asfap_backend_js_obj.ajax_nonce87 },88 beforeSend: function (xhr) {89 $('.asap-ajax-loader').css('visibility','visible');90 $('.asap-ajax-loader').css('opacity',1);91 },92 success: function (res) {93 //console.log(res.result);94 if(res.type == 'success'){95 $('#asap-error-msg').html(res.message).css({color:'green'}).delay(2000).fadeOut();96 dropdown.empty();97 $.each(res.result, function(key, value) {98 if(key == "fap_user_accounts"){99 $.each(this, function(k, v) {100 if(k == "auth_accounts"){101 $.each(this, function(akey, avalue) {102 var auth_key = akey;103 var auth_value = avalue;104 dropdown.append($('<option></option>').attr('value', auth_key).text(auth_value)); 105 });106 }107 });108 } 109 });110 // To encode an object (This produces a string)111 var json_str = JSON.stringify(res.result);112 $('textarea#asap-account-all-json').html('');113 $('textarea#asap-account-all-json').html(json_str);114 }115 else{116 $('#asap-error-msg').html(res.message).css({color:'red'});117 }118 $('.asap-ajax-loader').css( 'visibility' , 'hidden' );119 $('.asap-ajax-loader').css( 'opacity', 0 );120 }121 });122 });123124125 126 127 });//document.ready close
...
asap-src-test.js
Source:asap-src-test.js
1let { join } = require('path')2let test = require('tape')3let mockFs = require('mock-fs')4let sut = join(process.cwd(), 'src', 'lib', 'asap-src')5let asapSrc = require(sut)6let cwd = process.cwd()7test('Set up env', t => {8 t.plan(1)9 t.ok(asapSrc, 'ASAP src util is present')10})11test('Get ASAP', t => {12 t.plan(4)13 // Since we're developing Inventory locally (a scenario that bumps into asapSrc's business logic)14 // Temporarily change the src dir via cwd to prevent collisions15 // Work the src dir order backwards to test16 process.chdir(__dirname)17 let asap18 mockFs({})19 t.throws(() => {20 asapSrc()21 }, 'Throw if unable to find ASAP module')22 let localPath = join(cwd, 'node_modules', '@architect', 'asap', 'src')23 mockFs({ [localPath]: 'ok' })24 asap = asapSrc()25 t.equal(asap, localPath, `Got ASAP module in local dev mode: ${asap}`)26 process.chdir(cwd)27 let globalPath = join(cwd, '..', 'asap', 'src')28 mockFs({ [globalPath]: 'ok' })29 asap = asapSrc()30 t.equal(asap, globalPath, `Got ASAP module in global mode: ${asap}`)31 mockFs.restore()32 process.chdir(cwd) // Restore again, looks to be a mockFs restore bug mutating cwd33 let src = localPath // It's ok, this is the known collision when working locally34 asap = asapSrc()35 t.equal(asap, src, `Got ASAP module as a normal dependency: ${asap}`)...
index.js
Source:index.js
1// IMPORTING A MODULE2import asap from './asap_module';3function asapLog() {4 asap(()=>console.log('async'));5 console.log('sync');6}7window.asapLog = asapLog;8// NAMED IMPORT9// import { ASAP_CONST } from './asap_module';10// console.log('ASAP_CONST', ASAP_CONST);11// import asap, { ASAP_CONST } from './asap_module';12// CONVENIENCES13// Renaming named imports14// import { ASAP_CONST as some_const } from './asap_module';15// console.log('some_const', some_const);16// import { blaBlaBla } from './asap_module';17// console.log(blaBlaBla());18// Grouping named imports...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'google.png' });7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: 'google.png' });15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: 'google.png' });23 await browser.close();24})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: `example.png` });7 await browser.close();8})();9- **Yashwanth Kumar** - _Initial work_ - [yashwanthkumar](
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'example.png' });7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: 'example.png' });15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: 'example.png' });23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.screenshot({ path: 'example.png' });31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.screenshot({ path: 'example.png' });39 await browser.close();40})();41const { chromium } = require('playwright');42(async () => {43 const browser = await chromium.launch();44 const context = await browser.newContext();45 const page = await context.newPage();46 await page.screenshot({ path: 'example.png' });47 await browser.close();48})();49const { chromium } = require('playwright');
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.screenshot({ path: 'google.png' });6 await browser.close();7})();8const { chromium } = require('playwright');9(async () => {10 const browser = await chromium.launch();11 const page = await browser.newPage();12 await page.screenshot({ path: 'google.png' });13 await browser.close();14})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.screenshot({ path: `example.png` });6 await browser.close();7})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const page = await browser.newPage();5 await page.screenshot({ path: `example.png` });6 await browser.close();7})();8const { chromium } = require('playwright');9(async () => {10 const browser = await chromium.launch({ headless: false });11 const page = await browser.newPage();12 await page.screenshot({ path: `example.png` });13 await browser.close();14})();15const { chromium } = require('playwright');16(async () => {17 const browser = await chromium.launch({ headless: false });18 const context = await browser.newContext();19 const page = await context.newPage();20 await page.screenshot({ path: `example.png` });21 await browser.close();22})();23const { chromium } = require('playwright');24(async () => {25 const browser = await chromium.launch({ headless: false });26 const page = await browser.newPage();27 await page.screenshot({ path: `example.png` });28 await browser.close();29})();
Using AI Code Generation
1const { chromium } = require('playwright');2const fs = require('fs');3const path = require('path');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: 'google.png' });9 await browser.close();10})();11const { chromium } = require('playwright');12const fs = require('fs');13const path = require('path');14(async () => {15 const browser = await chromium.launch();16 const context = await browser.newContext();17 const page = await context.newPage();18 await page.screenshot({ path: 'google.png' });19 await browser.close();20})();21const { chromium } = require('playwright');22const fs = require('fs');23const path = require('path');24(async () => {25 const browser = await chromium.launch();26 const context = await browser.newContext();27 const page = await context.newPage();28 await page.screenshot({ path: 'google.png' });29 await browser.close();30})();31const { chromium } = require('playwright');32const fs = require('fs');33const path = require('path');34(async () => {35 const browser = await chromium.launch();36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.screenshot({ path: 'google.png' });39 await browser.close();40})();41const { chromium } = require('playwright');42const fs = require('fs');43const path = require('path');44(async () => {45 const browser = await chromium.launch();46 const context = await browser.newContext();47 const page = await context.newPage();48 await page.screenshot({ path: 'google.png' });49 await browser.close();50})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({4 });5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.click('[placeholder="Search"]');
Using AI Code Generation
1const playwright = require('playwright');2const {devices} = require('playwright');3(async () => {4 const browser = await playwright.chromium.launch();5 const context = await browser.newContext({6 viewport: { width: 414, height: 896 },7 });8 const page = await context.newPage();9 await page.screenshot({ path: `example.png` });10 await browser.close();11})();12const playwright = require('playwright');13const {devices} = require('playwright');14(async () => {15 const browser = await playwright.chromium.launch();16 const context = await browser.newContext({17 viewport: { width: 414, height: 896 },18 });19 const page = await context.newPage();20 await page.screenshot({ path: `example.png` });21 await browser.close();22})();23const playwright = require('playwright');24const {devices} = require('playwright');25(async () => {26 const browser = await playwright.chromium.launch();27 const context = await browser.newContext({28 viewport: { width: 414, height: 896 },29 });30 const page = await context.newPage();31 await page.screenshot({ path: `example.png` });32 await browser.close();33})();34const playwright = require('playwright');35const {devices} = require('playwright');36(async () => {37 const browser = await playwright.chromium.launch();38 const context = await browser.newContext({39 viewport: { width: 414, height: 896 },40 });41 const page = await context.newPage();42 await page.screenshot({ path: `example.png` });
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!