0

I am working on a simple application that will go through DialogFlow (Google) and send me the intents that were picked up based on the users comment.

I have the following code.

let writeToExcel = [];



 var promises = xlData.map(data => {
   detectIntentText(data.QUESTION);
 });

 Promise.all(promises).then(function(results) {
   console.log(results);
   console.log(writeToExcel);
 })

However, the array that prints is all undefined, and it prints before the function, detectIntentText, finished everything in the map. There could be upwards of 1000 entries.

What is the best way to get this to work?

Here is the detectIntentText function

async function detectIntentText(userText) {
  const sessionId = Math.random().toString(36).substring(7);
  const sessionPath = client.projectLocationAgentSessionPath(
    projectId,
    location,
    agentId,
    sessionId
  );
  console.info(sessionPath);

  const request = {
    session: sessionPath,
    queryInput: {
      text: {
        text: userText,
      },
      languageCode,
    },
  };
  const [response] = await client.detectIntent(request);
  // console.log(`User Query: ${userText}`);
  var intent = "";
  for (const message of response.queryResult.responseMessages) {
    if (message.text) {
      // console.log(`Agent Response: ${message.text.text}`);
    }
  }
  if (response.queryResult.match.intent) {
    // console.log(
    //   `Matched Intent: ${response.queryResult.match.intent.displayName}`
    //);
    intent = response.queryResult.match.intent.displayName;
  }
  // console.log(
  //   `Current Page: ${response.queryResult.currentPage.displayName}`
  // );

  let jsonToWrite = {
    CX_QUESTION: userText,
    INTENT: intent
  }

  // console.log(jsonToWrite);

  writeToExcel.push(jsonToWrite);
}
newPHPDev
  • 33
  • 5
  • 2
    what is `detectIntentText()` ? is that async function? – BadPiggie Oct 19 '21 at 16:18
  • 1
    The expression `data => {…}` doesn't return a promise. – canon Oct 19 '21 at 16:19
  • 1
    You either need to remove the braces `.map(data => detectIntentText(data.QUESTION))` or you need a `return` as in: `.map(data => { return detectIntentText(data.QUESTION); })` – Wyck Oct 19 '21 at 16:23

1 Answers1

3

You are not returning anything from map. If detectIntentText() returns Promise, Then your code should be

 var promises = xlData.map(data => {
   return detectIntentText(data.QUESTION);
 });

 Promise.all(promises).then(function(results) {
   console.log(results);
   console.log(writeToExcel);
 })

You can get rid of the return keyword like this,

var promises = xlData.map(data => detectIntentText(data.QUESTION));
BadPiggie
  • 5,471
  • 1
  • 14
  • 28