0

I have two async/await function, first one is taking images and get response of images text, Second one needs to take response of first function as a parameter.

First async function

const detecText = async (filename) => {
  let [result] = await client.textDetection(filename);
  const labels = result.textAnnotations[0].description;
  return labels;
};

as I am using this detecText() function with multiple parameter from array ImagesName[]

    ImagesNames.forEach((element) => {
    detecText(element)
      .then((result) => {
     console.log(result);
      })
      .catch((err) =>
        console.log(
          "loop not working!" +
            err +
            element
        )
      );
  
  }); 

Now I have second async/await function which has to take parameter from above detecText() function

const target = "en";

const translateText = async function translateText(text) {
  let [translations] = await translate.translate(text, target);
  translations = Array.isArray(translations) ? translations : [translations];

  translations.forEach((translation, i) => { 
    return translation;
  });
};

How can I use this translateText() function with parameter from the response of deteText() function ?

kate moss
  • 416
  • 1
  • 5
  • 18

1 Answers1

1

Basically you can call your function translateText in the callback for then after the call of detecText.

You can do both ways:

detecText(element).then((result) => {
  return translateText(result);
})

// or simplified

detecText(element).then(translateText);

Second problem, is to wait for all the promises and getting all results in one place. For that you might need Promise.all.

  let translations;

  try {
    const translationPromises = ImagesNames.map((element) => {
      return detecText(element).then(translateText);
    };
    translations = await Promise.all(translationPromises);
  } catch (err) {
    console.log('o_O error', err);
  }

Overall, I'd advice you to get more practice with Promise API first, not with async/await sugar.

steppefox
  • 1,784
  • 2
  • 14
  • 19
  • How can I write each response in separate .txt file from `detecText(element).then((result) => { return translateText(result); }) ` – kate moss Aug 26 '22 at 11:15