How to improve async in this case

Asked

Viewed 62 times

-2

I’m using Chromium’s standard Bluetooth API, it makes the bluetooth connection by taking its services and features so I can finally use the methods that features and everything asynchronous, ok until then.

It happens 1 problem that the printer only prints a certain amount of characters because of the byte limitation so I decided to do a for printing letter by letter (a gambiarra that comes in handy mt well), so it prints as many as I want. The other problem is: the for only works if I put Alert(testo[i]) working as a pause to wait for the Promise to resolve.

Once they understand what I did, finally the question: How do I use the Promise correctly to print the next letter only when the other Promise has resolved or Rejected without using Alert?

I know which text is x, don’t notice the variable name

With Gabriel’s response the code became:

const imprimir = (letra) => printCharacteristic.writeValue(letra).catch((e) => console.log(e.message));

testo.split('').forEach(
  async (letra) => {
    //alert("a")
    encoded = encoder.encode(letra);
    console.log(letra);
    await imprimir(encoded)
  }
);

Diferença com alert e sem alert

I forgot to post the solution, I found it a day after posting here...

See the whole file in my git

What I did was split the string into pieces of up to 18 characters (because there was a byte limit), after which one was async for each item of the letter variable array. Each item had to wait 500 ms to send the print command to the printer, thus making everything work fine :D . Doing some tests, I noticed that the model of my printer printava tmb without qqer problems in 200ms.

I thank everyone who tried to help. Thank you

  • Since printCharacteristic.writeValue(letter) is already a prop, you don’t need to create a new one as you are doing. You can do like this: const print = (letter) => printCharacteristic.writeValue(letter) And the iteration, you can do like this: text.foreach(async(letter) => { encoded = Encoder.Encode(testo[i]); await print(encoded) })

  • Perfect, you understood exactly what I meant. Your code works with a simple change to the text.split('). foreach(...). These are the log console I did: p:143 t p:143 e p:143 s p:143 t 3 GATT Operation already in Progress. -> 4 letters typed, 3 letters dropped in the Promise catch() p:164 Printed en 2 -> only ONE letter printed here With Alert("a") the code still works "perfect" printing tds letters async (letter) => { Alert("a") encoded = Encoder.Encode(letter); await print(encoded) });

  • If it worked, put as answer guys!

  • It hasn’t worked yet, Samuel :(

  • Could use Promise.all to expect all results, I believe it will be much simpler than creating a chain.

  • @Guillhermenascimento, the problem of using Promise.all in this case is that this method does not execute the promises in sequence, but in parallel. And this may not be what the AP wants. See an example of this here.

  • 1

    @Luizfelipe is absolutely right, but in case if you "enumerate" inside the loop you have how to create an Dice to know the desired order and reorder at the end, of course this will go much more than using a loop, but it is still part of creating a necessary logic :)

  • Completely valid! : ) I had never even thought about it and liked the idea. : v

Show 3 more comments

1 answer

1

The method forEach array is not ideal to deal with promises. To deal with promise lists, I suggest you use the Array.prototype.map with Promise.all or use a repeat loop for within an asynchronous function.

As in your case the order of execution of promises is important, the second alternative (tie for) is a little more advantageous. So you can do something like this:

const print = (letter) => printCharacteristic
  .writeValue(letter)
  .catch((e) => console.log(e.message));

(async () => {
  const letters = text.split('');

  // Iteramos sobre cada letra:
  for (const letter of letters) {
    await print(letter);
    // A próxima iteração só acontecerá após a resolução dessa promisse.
  }
})();
  • Exactly, giving a researched I saw that the foreach does not deal with promises, I found a very good article in Medium that saved my life haha. https://medium.com/@mathiasghenoazzolini/javascript-loops-com-async-await-8b07caf38017

Browser other questions tagged

You are not signed in. Login or sign up in order to post.