Javascript promises and web workers (multithreading)

I have about 9000 images in a webpage that need to be loaded when the page loads. They are currently fetched using Promise and resolve.

There is some code that executes when all promises resolve.

Is the loading of the images being done on the main thread? If I encapsulate the promise in a web worker will it be faster? Also, if it is faster do you have any resources on how to do this?

Thank you in advance!

This app promises to run fstrim without root but I am not sure if itnworks

Here’s the link:

I am not sure if this app works. Can someone please help me? My phone is new and in its warranty period so I can’t root it yet. I tried this app but I am not sure if it actually did something. Unlike the other famous app on the play store for fstrim, it doesn’t require root access which is quite incredible.

An app on the play store promises to trim without root access but I highly doubt if it even works

My phone is new so I can’t root it because I don’t wanna void my warranty just yet and trimming my phone would also not make a significant difference. Since most other apps on the play store promise to run trim only with root access, I don’t think it’s possible for this app to do so without root but if it can that’s the best thing i can get. Can someone please excuse my stupidity and confirm if this app actually works? It will be really helpful.

Link to the app:

FIREBASE – Encadear promises para redirecionar página somente após salvar dados no Firestore Firebase e atualizar Display name

Fala, pessoal. Tudo bem?

Estou desenvolvendo uma aplicação web com o Firebase e como o método auth() só aceita e-mail e senha, estou atualizando o displayName e salvando o restando dos dados (cpf, por exemplo) no Firestore, no momento de criação do usuário.

Até aí, tudo certo. Porém, empaquei ao tentar redirecioná-lo para à nova página, APÓS esses processos (displayName e Firestore).

Primeiro, chamei as funções de displayName, Firestore e redirecionamento (usei o window.location.href) no .then do auth().createUserWithEmailAndPassword(email, password), mas redirecionava antes de realizar os processos.

Depois tentei encadeá-los em promises, mas não deu muito certo.

document.getElementById('buttonSignupUser').addEventListener('click', function() {     var email = document.getElementById('inputEmail').value;     var password = document.getElementById('password').value;     var password2 = document.getElementById('password2').value;      if (password == password2){         firebase.auth().createUserWithEmailAndPassword(email, password)             .then(function() {                 console.log('user created');                 saveFirestore();             }).then(function(){                 addDisplayName();             }).then(function(){                 redirectSignup();             })             .catch(function(error) {                 if (error.code == 'auth/invalid-email') {                     console.log('Por favor, digite um e-mail válido');                 } else if (error.code == 'auth/email-already-in-use') {                     console.log('Esse e-mail já está sendo utilizado');                 }              });     } else {         console.log('As senhas devem ser iguais');     }  }) 

Essa é a função para salvar os dados complementares no Firestore:

function saveFirestore(){     var email = document.getElementById('inputEmail').value;     var name = document.getElementById('inputName').value;     var cpf = document.getElementById('inputCPF').value;      var user = firebase.auth().currentUser;     var uid;          if (user != null) {         uid = user.uid;           }      firebase.firestore().collection('usuario').doc(uid).set({         CPF: cpf,         Email: email,         Nome: name,         Id: uid     })     console.log('saved firestore'); } 

Essa é a função para atualizar o valor displayName

function addDisplayName(){     var name = document.getElementById('inputName').value;         firebase.auth().currentUser.updateProfile({         displayName: name         }).then(function() {             console.log('Display name added');         }).catch(function(error) {             console.log(error);         }); } 

E por último, essa é a para redirecionar o usuário

function redirectSignup(){     window.lotacion.href='logado.html' }  

Passei o dia tentando resolver isso, li sobre encadeamento de promises, promises.all, async/await, tentei usar um if/else…mas como estudo Javascript há pouco tempo, muitos assuntos ainda são complexos e, por isso, não consegui resolver.

Já agradeço a atenção, pessoal. Abraços

How to chain promises for multiple ajax calls to SharePoint to get user ids?

Broken promises, thought I had it figured out, still trying to get reliable results. Console log shows hit and miss results. Below is the rundown of what I’m trying to achieve. Is there a simpler way to do this, I’ve been struggling with this for a week now just to update person fields, its ridiculous.

  • I have 2 multiperson people pickers in SharePoint.
  • MS gives you every user detail EXCEPT the user id which is needed to update via ajax
  • I can get the emails from the people pickers into arrays
  • My promises setup is hit and miss retrieving id’s
  • When it works it outputs a string array that doesn’t work with updating field

    eg: 1,2,3,4 instead of [1,2,3,4]

function test1a() {

    fEmailArray = [];     tEmailArray = [];     fIdArray = [];     tIdArray = [];      var FCon = $  ("div[title='From Contacts'] > input").val();     var Fjson = JSON.parse(FCon);     for (var i = 0; i < Fjson.length; i++) {         fEmailArray.push(Fjson[i].EntityData.Email);     }      var TCon = $  ("div[title='To Contacts'] > input").val();     var Tjson = JSON.parse(TCon);     for (var i = 0; i < Tjson.length; i++) {         tEmailArray.push(Tjson[i].EntityData.Email);     }      let promiseF = => test2(fEmail));     let promiseT = => test2(tEmail));      return Promise.all(promiseF)         .then(function (data) { fIdArray = data; })         .then(Promise.all(promiseT)         .then(function (data) { tIdArray = data; }));             }  function test2(xEmail) {      let myPromise = new Promise((resolve, reject) => {         $  .ajax({ // get the Ids of users             url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/SiteUsers?$  select=Id&$  filter=Email eq '" + xEmail + "'",             type: "GET", headers: { "Accept": "application/json;odata=verbose", },             success: function (data) {                 var xuserid = data.d.results[0].Id;                 resolve(xuserid);             },             error: function (error) {                 alert(JSON.stringify(error));                 reject();             }         });     });     return myPromise; } // end test2 

Use of Javascript Promises

I have created a small static site generator (for learning purposes) in Javascript ES6, using Promises, however, I am not certain of how to use them well. The code below works fine, but I wonder if i can’t write my promises a better way.

I call my promises in SSG.start();

const yaml = require('js-yaml'); const fs   = require('fs-extra'); const ejs  = require('ejs'); const md   = require('markdown-it')({     html: true,     linkify: true,     typographer: true });  let SSG = {     outputFolder: '../output/',      contentFolder: '../content/',      assetsFolder: '../assets/',      contentFiles: async function (dir, filelist) {         return new Promise((resolve) => {             files = fs.readdirSync(dir);             filelist = filelist || [];             files.forEach((file) => {                 if (fs.statSync(dir + '/' + file).isDirectory()) {                     return resolve(contentFiles(dir + '/' + file, filelist));                 } else {                     filelist.push(file);                     return resolve(filelist);                 }             });         })     },      generateHTMLFile: async function (file) {         return new Promise((resolve) => {             let fstream = fs.readFileSync(file, 'utf8');             let params = fstream.match(/\+Params\+([\s\S]*?)\+\+\+/g);             let content = fstream.match(/(\+Content[0-9]*\+|\+Content\+)([\s\S]*?)*(\+\+\+)/g);             let contents = [];              params = params[0].replace('+Params+', '').replace('+++', '');             content = content[0].split('+++');              try {                 params = yaml.safeLoad(params, 'utf8');                 for (it of content) {                     it = it.replace('+++', '').replace(/(\+Content[0-9]*\+|\+Content\+)/g, '');                     contents.push(md.render(it));                 }                  const funs = require('./functions.js');                  ejs.renderFile('../templates/' + params.template + '.ejs', {funs: funs, params: params, content: contents}, {}, (err, html) => {                     if (err) console.log(err);                     resolve({html: html, url: params.url});                 });              } catch (e) {                 console.log(e);             }         });     },      saveHTML: function (html, url) {         if (!fs.existsSync(this.outputFolder)) {             fs.mkdir(this.outputFolder, { recursive: true }, (err) => {                 if (err) throw err;             });         }         fs.writeFile(this.outputFolder + url + '.html', html, (err) => {             if (err)  return console.log(err);         });     },      saveStaticAssets: function () {         fs.copySync(this.assetsFolder, this.outputFolder);     },      start: async function () {         try {             let time =;             console.log('Génération des fichiers HTML...');              let files = await this.contentFiles(this.contentFolder);              for (file of files) {                 await this.generateHTMLFile(this.contentFolder + file).then(({html, url}) => {                     this.saveHTML(html, url);                 });             }              this.saveStaticAssets();              console.log('Généré en ' + ( - time) + 'ms');         } catch (e) {             console.error(e.message);         }     } };  (async () => {     await SSG.start(); })();  

What do you think about it ?

Uso de método finally en promises en JavaScript

Típicamente este es un ejemplo sencillo de una Promise en JavaScript

let app = new Promise((resolve, reject) => {   let numero = 2   resultado = (numero % 2 === 0) ? true : false   resolve(resultado)   reject(0) }) 

La cual a través de la variable app accedemos a lo que procesa y nos puede devolver

app.then(res => {   console.log(res) }).catch((e) => {   console.log(e) }) 

Donde identificamos lo siguiente

  • then retorna el resultado cuando la promise se resuelve correctamente
  • catch procesa el posible error que enfrente la promise y por el cual no sea capaz de devolver un resultado exitoso

Sin embargo investigando aquí finally encuentro que puedes encadenar otro método llamado finally el cual según la misma fuente sirve para y cito:

Devuelve una promise cuando esta se resuelve, sea exitosa o rechazada

Entonces genero este ejemplo

let app = new Promise((resolve, reject) => {   let numero = 2   resultado = (numero % 21 === 0) ? true : fadlse   resolve(resultado)   reject(0) })  app.then(res => {   console.log(res) }).catch((e) => {   console.log(e) }).finally(() => {   console.log("Procesada con exito o fallos") }) 

El cual por supuesto al tener fadlse me dará este error

[object Error] { … }

Pero el método finally se procesa de acuerdo a la definición citada y me retorna esto

“Procesada con exito o fallos”

Aclaro NO busco opiniones, pero dado que finally retorna algo independiente de que la promise sea o no resuelta, ¿cuál es uso práctico de este método?

Why does Babel convert async/await to generator functions rather than promises?

It’s a bit of a moot point now that async/await is supported by all major, modern JavaScript engines, but I’ve always wondered why Babel converts async functions to generator functions rather than to Promises, since async/await is just syntactic sugar for promises in the first place.

It looks like generators came in in ES5, promises were introduced in ES6, and async/await was in the ES7 standard, so I’m guessing that after the regenerator runtime was written in ES5, the Babel folks just didn’t see a point in rewriting it to use promises. But, if there’s another reason, I’m curious.

Chaining RXJs promises Observable.from

In RxJS 6, how can I chain and pass data with promises? I have to do a bunch of JIRA api calls in a row using the jira-connector npm library. But I’m not sure how to execute and pass the data to functions.



    const pipeData = Observable.from({         jql: 'team = 41 and type = "Initiative"'     }))      pipeData.pipe(         data => operators.flatMap(data.issues),         issue => Observable.from({         jql: `team = 41 and "Parent Link" = $  {issue.key}`     }))).subscribe(results => {         console.log(results)     })