Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

103
Visualizações
Get Promise resolve from separate callback

I am sending data to a Bluetooth device, and the responses are handled by a listener that's set up during the connection process:

device.connect().then(device => {
  device.registerResponseListener((data) => {
    // handle response
  }
}

I have a separate function that sends data to the device:

const sendData = (device, data) => {
  device.write(data);
}

My question is, how can I Promisify this code? I'd like to be able to do

const sendData = (device, data) => {
  return new Promise((resolve, reject) => {
    device.write(data);
    // resolve...?
  });
}

But how do I get the resolve into the Bluetooth response listener?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I don't know what API you're using but you can try BluetoothRemoteGATTCharacteristic API. It has writeValueWithResponse method which return Promise.

https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTCharacteristic

about 4 years ago · Juan Pablo Isaza Relatório

0

The best possible solution in this case, while still not ideal, was to store the resolve function in variable at a higher scope:

var sendDataResolve;

device.connect().then(device => {
  device.registerResponseListener((data) => {
    sendDataResolve(data);
  }
}

const sendData = (device, data) => {
  return new Promise((resolve, reject) => {
    sendDataResolve = resolve;
    device.write(data);
  });
}

...

sendData(device, "data")
.then(result => {
  console.log("Got result",result);
});

The caveat is that Promise resolutions are NOT guaranteed to be tied correctly to the original request. This ONLY works with one request at a time.

about 4 years ago · Juan Pablo Isaza Relatório

0

If I understood you correctly then you can do it like this

const sendData = async (device, data) => {
  const response = await device.write(data);
  await Promise.all(device.responseListeners.map(listener => listener(response)))
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda