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

194
Visualizações
Javascript Anti-Pattern - Returning a new Promise from async function

Is returning an unresolved manually created Promise from an async function considered an anti-pattern?

As async functions return promises by default, it is a little strange to build a new Promise and return it from the same async function.

I have two different methods, in the first one, I have doubts as to whether or not I am doing the new Promise constructor anti-pattern. In the other one, I am definitely sure that it is an anti-pattern.

First function:

export default async (uri) => {
  const blob = await new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();

    xhr.onload = function () {
      resolve(xhr.response);
    };

    xhr.onerror = function (e) {
      reject(new TypeError("Network request failed"));
    };

    xhr.responseType = "blob";
    xhr.open("GET", uri, true);
    xhr.send(null);
  });

  return blob;
};

Second function:

export async function uploadImageToStorage(
  imageUri,
  storageFolder = "images",
  stateObserver = undefined
) {
  const blob = await uriToBlob(imageUri);

  const imageId = blob._data.blobId;

  const storageRef = storage.ref(storageFolder).child(imageId);

  return new Promise((resolve, reject) => {
    storageRef.put(blob).on(
      "state_changed",
      stateObserver,
      function error(err) {
        blob.close();
        reject(err);
      },
      function complete() {
        blob.close();
        resolve(imageId);
      }
    );
  });
}

Is it considered to be an anti-pattern the first method implementation?

In the second function, as storageRef.put(blob).on() doesn't return a Promise, my api is callback-based, I need to wrap it inside a Promise, resolving in a complete() callback. If I refactor it to:

export async function uploadImageToStorage(
  imageUri,
  storageFolder = "images",
  stateObserver = undefined
) {
  const blob = await uriToBlob(imageUri);

  const imageId = blob._data.blobId;

  const storageRef = storage.ref(storageFolder).child(imageId);

  await new Promise((resolve, reject) => {
    storageRef.put(blob).on(
      "state_changed",
      stateObserver,
      function error(err) {
        blob.close();
        reject(err);
      },
      function complete() {
        blob.close();
        resolve(imageId);
      }
    );
  });
  
  return imageId;
}

The new implementation would not be considered as an anti-pattern right?

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

0

There is nothing wrong with this in either case. You have to return a Promise, but the API you are using is callback-based, so you have to wrap it in a manually created Promise at some point.

However, there's no point awaiting that Promise within your async function if all you're going to do is return the value that it resolved to. In that case you can just return the unresolved Promise directly.

After doing that, if you are no longer using await in the function, you could also remove the async keyword. But I would leave it in as a signal to the casual reader that the return value will be a Promise.

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