Best JavaScript code snippet using wpt
Task.ts
Source: Task.ts
1/*2 * CloudBeaver - Cloud Database Manager3 * Copyright (C) 2020-2022 DBeaver Corp and others4 *5 * Licensed under the Apache License, Version 2.0.6 * you may not use this file except in compliance with the License.7 */8import { computed, makeObservable, observable } from 'mobx';9import type { ITask } from './ITask';10export class Task<TValue> implements ITask<TValue> {11 cancelled: boolean;12 executing: boolean;13 get cancellable(): boolean {14 if (15 this.cancelled16 || (this.externalCancel === undefined && this.executing)17 ) {18 return false;19 }20 if (this.externalCancel !== undefined) {21 return true;22 }23 if (this.sourcePromise instanceof Task) {24 return this.sourcePromise.cancellable;25 }26 return false;27 }28 private resolve!: (value: TValue) => void;29 private reject!: (reason?: any) => void;30 private innerPromise: Promise<TValue>;31 private sourcePromise: Promise<TValue> | null;32 get [Symbol.toStringTag](): string {33 return 'Task';34 }35 constructor(36 readonly task: () => Promise<TValue>,37 private externalCancel?: () => Promise<void> | void38 ) {39 this.innerPromise = new Promise((resolve, reject) => {40 this.reject = reject;41 this.resolve = resolve;42 });43 this.sourcePromise = null;44 this.cancelled = false;45 this.executing = false;46 makeObservable<this, 'sourcePromise'>(this, {47 cancellable: computed,48 cancelled: observable,49 executing: observable,50 sourcePromise: observable.ref,51 });52 }53 then<TResult1 = TValue, TResult2 = never>(54 onfulfilled?: ((value: TValue) => TResult1 | PromiseLike<TResult1>) | null,55 onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null56 ): ITask<TResult1 | TResult2> {57 return new Task(async () => {58 try {59 const value = await this.innerPromise;60 return await onfulfilled?.(value) as TResult1;61 } catch (e: any) {62 if (onrejected) {63 return await onrejected(e);64 }65 throw e;66 }67 }, () => this.cancel()).run();68 }69 catch<TResult = never>(70 onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null71 ): ITask<TValue | TResult> {72 return new Task(async () => {73 try {74 return await this.innerPromise;75 } catch (exception: any) {76 if (onrejected) {77 return await onrejected(exception);78 }79 throw exception;80 }81 }, () => this.cancel()).run();82 }83 finally(onfinally?: (() => void) | null): ITask<TValue> {84 return new Task(async () => {85 try {86 return await this.innerPromise;87 } finally {88 onfinally?.();89 }90 }, () => this.cancel()).run();91 }92 run(): this {93 if (this.cancelled) {94 return this;95 }96 if (this.executing) {97 throw new Error('Task already executing');98 }99 this.executing = true;100 this.sourcePromise = this.task();101 this.sourcePromise102 .then(value => this.resolve(value))103 .catch(reason => this.reject(reason))104 .finally(() => {105 this.executing = false;106 this.sourcePromise = null;107 });108 return this;109 }110 cancel(): Promise<void> | void {111 if (this.cancelled) {112 return;113 }114 this.cancelled = true;115 if (!this.executing) {116 this.reject(new Error('Task was cancelled'));117 return;118 }119 if (this.externalCancel) {120 return this.externalCancel();121 }122 if (this.sourcePromise instanceof Task) {123 return this.sourcePromise.cancel();124 }125 }...
api.js
Source: api.js
1import find from 'lodash/find';2import { TaskResource, ChannelResource, RemoteChannelResource } from 'kolibri.resources';3import { TaskTypes } from '../../constants';4import { NetworkLocationResource } from '../../apiResources';5const kolibriStudioUrl = 'https://studio.learningequality.org';6function getChannelOnDrive(driveId, channelId) {7 const reject = () => Promise.reject('CHANNEL_NOT_ON_DRIVE');8 return TaskResource.localDrives().then(response => {9 const drives = response.entity;10 const driveMatch = find(drives, { id: driveId });11 if (!driveMatch) {12 return reject();13 }14 const channelMatch = find(driveMatch.metadata.channels, { id: channelId });15 if (!channelMatch) {16 return reject();17 }18 return {19 ...channelMatch,20 driveId,21 };22 });23}24function getChannelOnPeer(addressId, channelId) {25 return NetworkLocationResource.fetchModel({ id: addressId })26 .then(location => {27 return RemoteChannelResource.fetchModel({28 id: channelId,29 getParams: {30 baseurl: location.base_url,31 },32 force: true,33 }).then(([channel]) => {34 return {35 ...channel,36 baseurl: location.base_url,37 };38 });39 })40 .catch(() => {41 return Promise.reject('CHANNEL_NOT_ON_PEER');42 });43}44function getChannelOnStudio(channelId) {45 return RemoteChannelResource.fetchModel({46 id: channelId,47 })48 .then(([channel]) => {49 return {50 ...channel,51 baseurl: kolibriStudioUrl,52 };53 })54 .catch(() => {55 return Promise.reject('CHANNEL_NOT_ON_STUDIO');56 });57}58function getInstalledChannel(channelId) {59 return ChannelResource.fetchModel({ id: channelId }).catch(() => {60 return Promise.reject('CHANNEL_NOT_INSTALLED');61 });62}63// Based on URL parameters from NewChannelVersionPage, fetches the channel64// to be installed. Returns errors if params are invalid.65export function fetchChannelAtSource(params) {66 const { channelId, driveId, addressId } = params;67 let sourcePromise;68 if (driveId) {69 sourcePromise = getChannelOnDrive(driveId, channelId);70 } else if (addressId) {71 sourcePromise = getChannelOnPeer(addressId, channelId);72 } else {73 sourcePromise = getChannelOnStudio(channelId);74 }75 return Promise.all([getInstalledChannel(channelId), sourcePromise]);76}77export function fetchOrTriggerChannelDiffStatsTask(params) {78 const { channelId, driveId, baseurl } = params;79 // Re-use the same object for lodash/find and making POST request.80 // Separate 'method' since it isn't part of Task metadata.81 let method;82 let taskAttrs = {83 channel_id: channelId,84 };85 if (baseurl) {86 taskAttrs.baseurl = baseurl;87 method = 'network';88 } else if (driveId) {89 taskAttrs.drive_id = driveId;90 method = 'disk';91 }92 return TaskResource.fetchCollection({ force: true }).then(tasks => {93 const match = find(tasks, { ...taskAttrs, type: TaskTypes.CHANNELDIFFSTATS });94 if (match) {95 return match;96 } else {97 return TaskResource.postListEndpoint('channeldiffstats', { ...taskAttrs, method }).then(98 taskResponse => taskResponse.entity99 );100 }101 });...
Layer.ts
Source: Layer.ts
...56 return { element, ...size };57 })58 .catch(() => console.error(ERROR_INVALID_SOURCE));59 };60 get sourcePromise() {61 return this.#state.sourcePromise;62 }63 get source() {64 return this.#state.source;65 }66 get size() {67 return this.#state.size;68 }69 get posX() {70 return this.#state.posX;71 }72 set posX(value) {73 if (typeof value === 'number') this.#state.posX = value;74 }...
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.error(err);4 wpt.getTestResults(data.data.testId, function(err, data) {5 if (err) return console.error(err);6 console.log(data);7 });8});
Using AI Code Generation
1var wptools = require('wptools');2var sourcePromise = wptools.page('Barack Obama').get().then(function(page) {3 return page.source();4});5sourcePromise.then(function(source) {6 console.log(source);7});8Promise {9 { status: 'success',
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org');3var options = {4};5wpt.runTest(url, options, function(err, data) {6 if (err) return console.error(err);7 console.log('Test status: %s', data.statusText);8 if (data.statusCode === 200) {9 console.log('Test completed in %d seconds', data.data.average.firstView.loadTime);10 console.log('View the test at %s', data.data.userUrl);11 }12});13var WebPageTest = function(server, key) {14 if (!(this instanceof WebPageTest)) {15 return new WebPageTest(server, key);16 }17 this._server = server;18 this._key = key;19};20WebPageTest.prototype.runTest = function(url, options, callback) {21 var self = this;22 var params = {23 };24 if (typeof options === 'function') {25 callback = options;26 } else {27 for (var k in options) {28 params[k] = options[k];29 }30 }31 if (this._key) {32 params.key = this._key;33 }34 var req = http.request({35 }, function(res) {36 var data = '';37 res.on('data', function(chunk) {38 data += chunk;39 });40 res.on('end', function() {41 if (res.statusCode === 200) {42 var json = JSON.parse(data);43 if (json.statusCode === 200) {44 self.sourcePromise(json.data.jsonUrl, params.pollResults, params.timeout)
Using AI Code Generation
1var wpt = require('webpagetest');2var api = new wpt('www.webpagetest.org', 'A.3a3b3c3d3e3f3g3h3i3j3k3l3m3n');3api.runTest(url, function(err, data) {4 if (err) {5 } else {6 api.getTestResults(data.data.testId, function(err, data) {7 if (err) {8 } else {9 console.log(data);10 }11 });12 }13});
Using AI Code Generation
1var wptSource = require('./wptSource');2var wptPromise = wptSource.sourcePromise();3var wptSource = wptPromise.then(function(wptSource) {4 return wptSource;5});6wptSource.then(function(wptSource) {7 wptSource.getData().then(function(data) {8 console.log(data);9 });10});11module.exports = function() {12 return sourcePromise();13};14var sourcePromise = function() {15 return new Promise(function(resolve, reject) {16 resolve({17 getData: function() {18 return new Promise(function(resolve, reject) {19 resolve('data');20 });21 }22 });23 });24};
Check out the latest blogs from LambdaTest on this topic:
Testing is a critical step in any web application development process. However, it can be an overwhelming task if you don’t have the right tools and expertise. A large percentage of websites still launch with errors that frustrate users and negatively affect the overall success of the site. When a website faces failure after launch, it costs time and money to fix.
We launched LT Browser in 2020, and we were overwhelmed by the response as it was awarded as the #5 product of the day on the ProductHunt platform. Today, after 74,585 downloads and 7,000 total test runs with an average of 100 test runs each day, the LT Browser has continued to help developers build responsive web designs in a jiffy.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!