How to use chunkPromise method in wpt

Best JavaScript code snippet using wpt

02_filereader.js

Source:02_filereader.js Github

copy

Full Screen

1// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.2// @ts-check3/// <reference no-default-lib="true" />4/// <reference path="../../core/lib.deno_core.d.ts" />5/// <reference path="../webidl/internal.d.ts" />6/// <reference path="../web/internal.d.ts" />7/// <reference path="../web/lib.deno_web.d.ts" />8/// <reference path="./internal.d.ts" />9/// <reference path="./lib.deno_file.d.ts" />10/// <reference lib="esnext" />11"use strict";12((window) => {13 const webidl = window.__bootstrap.webidl;14 const { forgivingBase64Encode } = window.__bootstrap.infra;15 const { decode, TextDecoder } = window.__bootstrap.encoding;16 const { parseMimeType } = window.__bootstrap.mimesniff;17 const state = Symbol("[[state]]");18 const result = Symbol("[[result]]");19 const error = Symbol("[[error]]");20 const aborted = Symbol("[[aborted]]");21 class FileReader extends EventTarget {22 get [Symbol.toStringTag]() {23 return "FileReader";24 }25 /** @type {"empty" | "loading" | "done"} */26 [state] = "empty";27 /** @type {null | string | ArrayBuffer} */28 [result] = null;29 /** @type {null | DOMException} */30 [error] = null;31 [aborted] = false;32 /**33 * @param {Blob} blob34 * @param {{kind: "ArrayBuffer" | "Text" | "DataUrl" | "BinaryString", encoding?: string}} readtype35 */36 #readOperation(blob, readtype) {37 // 1. If fr’s state is "loading", throw an InvalidStateError DOMException.38 if (this[state] === "loading") {39 throw new DOMException(40 "Invalid FileReader state.",41 "InvalidStateError",42 );43 }44 // 2. Set fr’s state to "loading".45 this[state] = "loading";46 // 3. Set fr’s result to null.47 this[result] = null;48 // 4. Set fr’s error to null.49 this[error] = null;50 // 5. Let stream be the result of calling get stream on blob.51 const stream /*: ReadableStream<ArrayBufferView>*/ = blob.stream();52 // 6. Let reader be the result of getting a reader from stream.53 const reader = stream.getReader();54 // 7. Let bytes be an empty byte sequence.55 /** @type {Uint8Array[]} */56 const chunks = [];57 // 8. Let chunkPromise be the result of reading a chunk from stream with reader.58 let chunkPromise = reader.read();59 // 9. Let isFirstChunk be true.60 let isFirstChunk = true;61 // 10 in parallel while true62 (async () => {63 while (!this[aborted]) {64 // 1. Wait for chunkPromise to be fulfilled or rejected.65 try {66 const chunk = await chunkPromise;67 if (this[aborted]) return;68 // 2. If chunkPromise is fulfilled, and isFirstChunk is true, queue a task to fire a progress event called loadstart at fr.69 if (isFirstChunk) {70 // TODO(lucacasonato): this is wrong, should be HTML "queue a task"71 queueMicrotask(() => {72 if (this[aborted]) return;73 // fire a progress event for loadstart74 const ev = new ProgressEvent("loadstart", {});75 this.dispatchEvent(ev);76 });77 }78 // 3. Set isFirstChunk to false.79 isFirstChunk = false;80 // 4. If chunkPromise is fulfilled with an object whose done property is false81 // and whose value property is a Uint8Array object, run these steps:82 if (!chunk.done && chunk.value instanceof Uint8Array) {83 chunks.push(chunk.value);84 // TODO(bartlomieju): (only) If roughly 50ms have passed since last progress85 {86 const size = chunks.reduce((p, i) => p + i.byteLength, 0);87 const ev = new ProgressEvent("progress", {88 loaded: size,89 });90 // TODO(lucacasonato): this is wrong, should be HTML "queue a task"91 queueMicrotask(() => {92 if (this[aborted]) return;93 this.dispatchEvent(ev);94 });95 }96 chunkPromise = reader.read();97 } // 5 Otherwise, if chunkPromise is fulfilled with an object whose done property is true, queue a task to run the following steps and abort this algorithm:98 else if (chunk.done === true) {99 // TODO(lucacasonato): this is wrong, should be HTML "queue a task"100 queueMicrotask(() => {101 if (this[aborted]) return;102 // 1. Set fr’s state to "done".103 this[state] = "done";104 // 2. Let result be the result of package data given bytes, type, blob’s type, and encodingName.105 const size = chunks.reduce((p, i) => p + i.byteLength, 0);106 const bytes = new Uint8Array(size);107 let offs = 0;108 for (const chunk of chunks) {109 bytes.set(chunk, offs);110 offs += chunk.byteLength;111 }112 switch (readtype.kind) {113 case "ArrayBuffer": {114 this[result] = bytes.buffer;115 break;116 }117 case "BinaryString":118 this[result] = [...new Uint8Array(bytes.buffer)].map((v) =>119 String.fromCodePoint(v)120 ).join("");121 break;122 case "Text": {123 let decoder = undefined;124 if (readtype.encoding) {125 try {126 decoder = new TextDecoder(readtype.encoding);127 } catch {128 // don't care about the error129 }130 }131 if (decoder === undefined) {132 const mimeType = parseMimeType(blob.type);133 if (mimeType) {134 const charset = mimeType.parameters.get("charset");135 if (charset) {136 try {137 decoder = new TextDecoder(charset);138 } catch {139 // don't care about the error140 }141 }142 }143 }144 if (decoder === undefined) {145 decoder = new TextDecoder();146 }147 this[result] = decode(bytes, decoder.encoding);148 break;149 }150 case "DataUrl": {151 const mediaType = blob.type || "application/octet-stream";152 this[result] = `data:${mediaType};base64,${153 forgivingBase64Encode(bytes)154 }`;155 break;156 }157 }158 // 4.2 Fire a progress event called load at the fr.159 {160 const ev = new ProgressEvent("load", {161 lengthComputable: true,162 loaded: size,163 total: size,164 });165 this.dispatchEvent(ev);166 }167 // 5. If fr’s state is not "loading", fire a progress event called loadend at the fr.168 //Note: Event handler for the load or error events could have started another load, if that happens the loadend event for this load is not fired.169 if (this[state] !== "loading") {170 const ev = new ProgressEvent("loadend", {171 lengthComputable: true,172 loaded: size,173 total: size,174 });175 this.dispatchEvent(ev);176 }177 });178 break;179 }180 } catch (err) {181 // TODO(lucacasonato): this is wrong, should be HTML "queue a task"182 queueMicrotask(() => {183 if (this[aborted]) return;184 // chunkPromise rejected185 this[state] = "done";186 this[error] = err;187 {188 const ev = new ProgressEvent("error", {});189 this.dispatchEvent(ev);190 }191 //If fr’s state is not "loading", fire a progress event called loadend at fr.192 //Note: Event handler for the error event could have started another load, if that happens the loadend event for this load is not fired.193 if (this[state] !== "loading") {194 const ev = new ProgressEvent("loadend", {});195 this.dispatchEvent(ev);196 }197 });198 break;199 }200 }201 })();202 }203 constructor() {204 super();205 this[webidl.brand] = webidl.brand;206 }207 /** @returns {number} */208 get readyState() {209 webidl.assertBranded(this, FileReader);210 switch (this[state]) {211 case "empty":212 return FileReader.EMPTY;213 case "loading":214 return FileReader.LOADING;215 case "done":216 return FileReader.DONE;217 default:218 throw new TypeError("Invalid state");219 }220 }221 get result() {222 webidl.assertBranded(this, FileReader);223 return this[result];224 }225 get error() {226 webidl.assertBranded(this, FileReader);227 return this[error];228 }229 abort() {230 webidl.assertBranded(this, FileReader);231 // If context object's state is "empty" or if context object's state is "done" set context object's result to null and terminate this algorithm.232 if (233 this[state] === "empty" ||234 this[state] === "done"235 ) {236 this[result] = null;237 return;238 }239 // If context object's state is "loading" set context object's state to "done" and set context object's result to null.240 if (this[state] === "loading") {241 this[state] = "done";242 this[result] = null;243 }244 // If there are any tasks from the context object on the file reading task source in an affiliated task queue, then remove those tasks from that task queue.245 // Terminate the algorithm for the read method being processed.246 this[aborted] = true;247 // Fire a progress event called abort at the context object.248 const ev = new ProgressEvent("abort", {});249 this.dispatchEvent(ev);250 // If context object's state is not "loading", fire a progress event called loadend at the context object.251 if (this[state] !== "loading") {252 const ev = new ProgressEvent("loadend", {});253 this.dispatchEvent(ev);254 }255 }256 /** @param {Blob} blob */257 readAsArrayBuffer(blob) {258 webidl.assertBranded(this, FileReader);259 const prefix = "Failed to execute 'readAsArrayBuffer' on 'FileReader'";260 webidl.requiredArguments(arguments.length, 1, { prefix });261 this.#readOperation(blob, { kind: "ArrayBuffer" });262 }263 /** @param {Blob} blob */264 readAsBinaryString(blob) {265 webidl.assertBranded(this, FileReader);266 const prefix = "Failed to execute 'readAsBinaryString' on 'FileReader'";267 webidl.requiredArguments(arguments.length, 1, { prefix });268 // alias for readAsArrayBuffer269 this.#readOperation(blob, { kind: "BinaryString" });270 }271 /** @param {Blob} blob */272 readAsDataURL(blob) {273 webidl.assertBranded(this, FileReader);274 const prefix = "Failed to execute 'readAsBinaryString' on 'FileReader'";275 webidl.requiredArguments(arguments.length, 1, { prefix });276 // alias for readAsArrayBuffer277 this.#readOperation(blob, { kind: "DataUrl" });278 }279 /**280 * @param {Blob} blob281 * @param {string} [encoding]282 */283 readAsText(blob, encoding) {284 webidl.assertBranded(this, FileReader);285 const prefix = "Failed to execute 'readAsBinaryString' on 'FileReader'";286 webidl.requiredArguments(arguments.length, 1, { prefix });287 if (encoding !== undefined) {288 encoding = webidl.converters["DOMString"](encoding, {289 prefix,290 context: "Argument 2",291 });292 }293 // alias for readAsArrayBuffer294 this.#readOperation(blob, { kind: "Text", encoding });295 }296 }297 webidl.configurePrototype(FileReader);298 Object.defineProperty(FileReader, "EMPTY", {299 writable: false,300 enumerable: true,301 configurable: false,302 value: 0,303 });304 Object.defineProperty(FileReader, "LOADING", {305 writable: false,306 enumerable: true,307 configurable: false,308 value: 1,309 });310 Object.defineProperty(FileReader, "DONE", {311 writable: false,312 enumerable: true,313 configurable: false,314 value: 2,315 });316 Object.defineProperty(FileReader.prototype, "EMPTY", {317 writable: false,318 enumerable: true,319 configurable: false,320 value: 0,321 });322 Object.defineProperty(FileReader.prototype, "LOADING", {323 writable: false,324 enumerable: true,325 configurable: false,326 value: 1,327 });328 Object.defineProperty(FileReader.prototype, "DONE", {329 writable: false,330 enumerable: true,331 configurable: false,332 value: 2,333 });334 const handlerSymbol = Symbol("eventHandlers");335 function makeWrappedHandler(handler) {336 function wrappedHandler(...args) {337 if (typeof wrappedHandler.handler !== "function") {338 return;339 }340 return wrappedHandler.handler.call(this, ...args);341 }342 wrappedHandler.handler = handler;343 return wrappedHandler;344 }345 // TODO(benjamingr) reuse when we can reuse code between web crates346 function defineEventHandler(emitter, name) {347 // HTML specification section 8.1.5.1348 Object.defineProperty(emitter, `on${name}`, {349 get() {350 return this[handlerSymbol]?.get(name)?.handler ?? null;351 },352 set(value) {353 if (!this[handlerSymbol]) {354 this[handlerSymbol] = new Map();355 }356 let handlerWrapper = this[handlerSymbol]?.get(name);357 if (handlerWrapper) {358 handlerWrapper.handler = value;359 } else {360 handlerWrapper = makeWrappedHandler(value);361 this.addEventListener(name, handlerWrapper);362 }363 this[handlerSymbol].set(name, handlerWrapper);364 },365 configurable: true,366 enumerable: true,367 });368 }369 defineEventHandler(FileReader.prototype, "error");370 defineEventHandler(FileReader.prototype, "loadstart");371 defineEventHandler(FileReader.prototype, "load");372 defineEventHandler(FileReader.prototype, "loadend");373 defineEventHandler(FileReader.prototype, "progress");374 defineEventHandler(FileReader.prototype, "abort");375 window.__bootstrap.fileReader = {376 FileReader,377 };...

Full Screen

Full Screen

21_filereader.js

Source:21_filereader.js Github

copy

Full Screen

1// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.2((window) => {3 const base64 = window.__bootstrap.base64;4 async function readOperation(fr, blob, readtype) {5 // Implementation from https://w3c.github.io/FileAPI/ notes6 // And body of deno blob.ts readBytes7 fr.aborting = false;8 // 1. If fr’s state is "loading", throw an InvalidStateError DOMException.9 if (fr.readyState === FileReader.LOADING) {10 throw new DOMException(11 "Invalid FileReader state.",12 "InvalidStateError",13 );14 }15 // 2. Set fr’s state to "loading".16 fr.readyState = FileReader.LOADING;17 // 3. Set fr’s result to null.18 fr.result = null;19 // 4. Set fr’s error to null.20 fr.error = null;21 // 5. Let stream be the result of calling get stream on blob.22 const stream /*: ReadableStream<ArrayBufferView>*/ = blob.stream();23 // 6. Let reader be the result of getting a reader from stream.24 const reader = stream.getReader();25 // 7. Let bytes be an empty byte sequence.26 //let bytes = new Uint8Array();27 const chunks /*: Uint8Array[]*/ = [];28 // 8. Let chunkPromise be the result of reading a chunk from stream with reader.29 let chunkPromise = reader.read();30 // 9. Let isFirstChunk be true.31 let isFirstChunk = true;32 // 10 in parallel while true33 while (!fr.aborting) {34 // 1. Wait for chunkPromise to be fulfilled or rejected.35 try {36 const chunk = await chunkPromise;37 // 2. If chunkPromise is fulfilled, and isFirstChunk is true, queue a task to fire a progress event called loadstart at fr.38 if (isFirstChunk) {39 queueMicrotask(() => {40 // fire a progress event for loadstart41 const ev = new ProgressEvent("loadstart", {});42 fr.dispatchEvent(ev);43 });44 }45 // 3. Set isFirstChunk to false.46 isFirstChunk = false;47 // 4. If chunkPromise is fulfilled with an object whose done property is false48 // and whose value property is a Uint8Array object, run these steps:49 if (!chunk.done && chunk.value instanceof Uint8Array) {50 chunks.push(chunk.value);51 // TODO: (only) If roughly 50ms have passed since last progress52 {53 const size = chunks.reduce((p, i) => p + i.byteLength, 0);54 const ev = new ProgressEvent("progress", {55 loaded: size,56 });57 fr.dispatchEvent(ev);58 }59 chunkPromise = reader.read();60 } // 5 Otherwise, if chunkPromise is fulfilled with an object whose done property is true, queue a task to run the following steps and abort this algorithm:61 else if (chunk.done === true) {62 queueMicrotask(() => {63 if (fr.aborting) {64 return;65 }66 // 1. Set fr’s state to "done".67 fr.readyState = FileReader.DONE;68 // 2. Let result be the result of package data given bytes, type, blob’s type, and encodingName.69 const size = chunks.reduce((p, i) => p + i.byteLength, 0);70 const bytes = new Uint8Array(size);71 let offs = 0;72 for (const chunk of chunks) {73 bytes.set(chunk, offs);74 offs += chunk.byteLength;75 }76 switch (readtype.kind) {77 case "ArrayBuffer": {78 fr.result = bytes.buffer;79 break;80 }81 case "Text": {82 const decoder = new TextDecoder(readtype.encoding);83 fr.result = decoder.decode(bytes.buffer);84 break;85 }86 case "DataUrl": {87 fr.result = "data:application/octet-stream;base64," +88 base64.fromByteArray(bytes);89 break;90 }91 }92 // 4.2 Fire a progress event called load at the fr.93 {94 const ev = new ProgressEvent("load", {95 lengthComputable: true,96 loaded: size,97 total: size,98 });99 fr.dispatchEvent(ev);100 }101 // 5. If fr’s state is not "loading", fire a progress event called loadend at the fr.102 //Note: Event handler for the load or error events could have started another load, if that happens the loadend event for this load is not fired.103 if (fr.readyState !== FileReader.LOADING) {104 const ev = new ProgressEvent("loadend", {105 lengthComputable: true,106 loaded: size,107 total: size,108 });109 fr.dispatchEvent(ev);110 }111 });112 break;113 }114 } catch (err) {115 if (fr.aborting) {116 break;117 }118 // chunkPromise rejected119 fr.readyState = FileReader.DONE;120 fr.error = err;121 {122 const ev = new ProgressEvent("error", {});123 fr.dispatchEvent(ev);124 }125 //If fr’s state is not "loading", fire a progress event called loadend at fr.126 //Note: Event handler for the error event could have started another load, if that happens the loadend event for this load is not fired.127 if (fr.readyState !== FileReader.LOADING) {128 const ev = new ProgressEvent("loadend", {});129 fr.dispatchEvent(ev);130 }131 break;132 }133 }134 }135 class FileReader extends EventTarget {136 error = null;137 readyState = FileReader.EMPTY;138 result = null;139 aborting = false;140 constructor() {141 super();142 }143 abort() {144 // If context object's state is "empty" or if context object's state is "done" set context object's result to null and terminate this algorithm.145 if (146 this.readyState === FileReader.EMPTY ||147 this.readyState === FileReader.DONE148 ) {149 this.result = null;150 return;151 }152 // If context object's state is "loading" set context object's state to "done" and set context object's result to null.153 if (this.readyState === FileReader.LOADING) {154 this.readyState = FileReader.DONE;155 this.result = null;156 }157 // If there are any tasks from the context object on the file reading task source in an affiliated task queue, then remove those tasks from that task queue.158 // Terminate the algorithm for the read method being processed.159 this.aborting = true;160 // Fire a progress event called abort at the context object.161 const ev = new ProgressEvent("abort", {});162 this.dispatchEvent(ev);163 // If context object's state is not "loading", fire a progress event called loadend at the context object.164 if (this.readyState !== FileReader.LOADING) {165 const ev = new ProgressEvent("loadend", {});166 this.dispatchEvent(ev);167 }168 }169 readAsArrayBuffer(blob) {170 readOperation(this, blob, { kind: "ArrayBuffer" });171 }172 readAsBinaryString(blob) {173 // alias for readAsArrayBuffer174 readOperation(this, blob, { kind: "ArrayBuffer" });175 }176 readAsDataURL(blob) {177 readOperation(this, blob, { kind: "DataUrl" });178 }179 readAsText(blob, encoding) {180 readOperation(this, blob, { kind: "Text", encoding });181 }182 }183 FileReader.EMPTY = 0;184 FileReader.LOADING = 1;185 FileReader.DONE = 2;186 const handlerSymbol = Symbol("eventHandlers");187 function makeWrappedHandler(handler) {188 function wrappedHandler(...args) {189 if (typeof wrappedHandler.handler !== "function") {190 return;191 }192 return wrappedHandler.handler.call(this, ...args);193 }194 wrappedHandler.handler = handler;195 return wrappedHandler;196 }197 // TODO(benjamingr) reuse when we can reuse code between web crates198 function defineEventHandler(emitter, name) {199 // HTML specification section 8.1.5.1200 Object.defineProperty(emitter, `on${name}`, {201 get() {202 return this[handlerSymbol]?.get(name)?.handler;203 },204 set(value) {205 if (!this[handlerSymbol]) {206 this[handlerSymbol] = new Map();207 }208 let handlerWrapper = this[handlerSymbol]?.get(name);209 if (handlerWrapper) {210 handlerWrapper.handler = value;211 } else {212 handlerWrapper = makeWrappedHandler(value);213 this.addEventListener(name, handlerWrapper);214 }215 this[handlerSymbol].set(name, handlerWrapper);216 },217 configurable: true,218 enumerable: true,219 });220 }221 defineEventHandler(FileReader.prototype, "error");222 defineEventHandler(FileReader.prototype, "loadstart");223 defineEventHandler(FileReader.prototype, "load");224 defineEventHandler(FileReader.prototype, "loadend");225 defineEventHandler(FileReader.prototype, "progress");226 defineEventHandler(FileReader.prototype, "abort");227 window.__bootstrap.fileReader = {228 FileReader,229 };...

Full Screen

Full Screen

getGeoCoords.mjs

Source:getGeoCoords.mjs Github

copy

Full Screen

...23 for (const address of addressList) {24 console.log(`\t- ${address.cep}`)25 promiseArray.push(() => fetchData(address))26 if (promiseArray.length === concurrent) {27 const promises = await chunkPromise(promiseArray, {28 concurrent,29 promiseFlavor: PromiseFlavor.PromiseAllSettled30 })31 const resolvedPromises = promises32 .filter(({ status }) => status !== 'rejected')33 const rejectedPromises = promises34 .filter(({ status }) => status === 'rejected')35 if (rejectedPromises.length) {36 console.warn(rejectedPromises)37 }38 if (resolvedPromises.length) {39 const values = resolvedPromises.map(promise => promise.value)40 await csvWriter.writeRecords(values)41 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wpt = require('wpt');2const wptPromise = wpt('API_KEY');3wptPromise.then(function (wpt) {4 }).then(function (data) {5 console.log(data);6 });7});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var page = wptools.page('Albert Einstein');3page.get().then(function(page) {4 console.log(page.data);5});6var wptools = require('wptools');7var page = wptools.page('Albert Einstein');8page.get().then(function(page) {9 console.log(page.data);10});11var wptools = require('wptools');12var page = wptools.page('Albert Einstein');13page.get().then(function(page) {14 console.log(page.data);15});16var wptools = require('wptools');17var page = wptools.page('Albert Einstein');18page.get().then(function(page) {19 console.log(page.data);20});21var wptools = require('wptools');22var page = wptools.page('Albert Einstein');23page.get().then(function(page) {24 console.log(page.data);25});26var wptools = require('wptools');27var page = wptools.page('Albert Einstein');28page.get().then(function(page) {29 console.log(page.data);30});31var wptools = require('wptools');32var page = wptools.page('Albert Einstein');33page.get().then(function(page) {34 console.log(page.data);35});36var wptools = require('wptools');37var page = wptools.page('Albert Einstein');38page.get().then(function(page) {39 console.log(page.data);40});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var chunkPromise = wptools.chunkPromise;3var chunkSize = 10;4var chunk = [];5var promises = [];6for (var i = 0; i < chunkSize; i++) {7 chunk.push(i);8 if (chunk.length === chunkSize || i === chunkSize - 1) {9 promises.push(chunkPromise(chunk));10 chunk = [];11 }12}13Promise.all(promises).then(function(results) {14 console.log(results);15});16var wptools = {};17wptools.chunkPromise = function(chunk) {18 return new Promise(function(resolve, reject) {19 setTimeout(function() {20 resolve(chunk);21 }, 1000);22 });23};24module.exports = wptools;

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful