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

211
Visualizações
Async/await is not working with mkdir() in a loop

I have a method that creates an order folder first, then creates multiple product subfolders in that order folder. And to each product folder, I move some images. I want all this to be done before the method returns true. I have wrote the following code but it not working as i expected.

The for loop stucks at await movefile and function does not execute further. I'm using async/await for the first time and have no idea why its happening. Can anyone please point out what I'm doing wrong or can it be done in a better way?

static async saveOrderPhotos(allProduct , transactionId) {

    var products = allProduct;
    var orderTransactionId = transactionId;
    var success = true;

    const makedir = promisify(fs.mkdir);
    const movefile = promisify(fsExtra.move);

    const movefiles = async (i) => {
     
      for (let j = 0; j < products[i].photos.length; j++) {
       await movefile(`public/uploads/orders/temporary/${Order.getfilename(products[i].photos[j])}`, `public/uploads/orders/${products[i].photos[j]}`, (err) => {
       });
       }
       console.log("Files moves for product-" , i+1);
      return true;

    }

    const createProductFolders = async () => {
     
      for (let i = 0; i < products.length; i++) {

        if (products[i].photos.length > 0) {
          await makedir(`public/uploads/orders/Order-${orderTransactionId}/Product-${i + 1}`, async () => {
            console.log("Product Directory Created");
            // then move files into the product folder
            await movefiles(i);
          });
        }

      }

      return true;

    }


    try {

      if (Order.hasPhotos(products)) {

      // create order folder
        await makedir(`public/uploads/orders/Order-${orderTransactionId}`, async () => {
          console.log("Order Directory Created");
          // then create product folder
          await createProductFolders();
       console.log("All Files moved");

        });
      }
      console.log("Returning true");
      return true;
    } catch (err) {
      console.log(err);
    }

  }

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

0

Do not pass a callback to movefile() and makedir() as the last argument. These are already promisified versions of the functions so the callback is used by that. They communicate back completion via their returned promise, not via a callback.

When you pass a callback, it screws up the arguments to the promisified version and the promise never gets its callback called so the promise never resolves and the code gets stuck.

Note, current versions of nodejs already have promisified versions of a bunch of functions. For example, you can directly use these that might be relevant to your code:

fs.promises.mkdir()
fs.promises.rename()
fs.promises.copyFile()
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