Looping an array returned by a service node

Hi, I am calling a service, which returns an array. This array contains questions which have to be answered by the applicant and the answers have to be saved by the bot. Is there any way to loop the array items, so that the bot asks each question and saves each response?
Afterwards, the bot will use all the responses to call another service

Thank you

One way you could do it is with bot actions. Here’s an example…Step-by-step instructions below.

Steps

  1. Init: This initiates our variables before the loop runs.

    1. Put a script node inside it:
    context.answers = [];
    context.currentQuestion = -1;
    
  2. NextQuestion: This increments the question iterator and checks whether there’s another question in the array.

    1. Put a script node inside it:

      context.currentQuestion += 1;
      context.areAnyQuestionsLeft = context.currentQuestion < context.myService.response.body.length;
      
    2. Create an if condition in the bot action’s connectors: If context.areAnyQuestionsLeft equals true, go to the Answer entity node. Otherwise, go to the UploadAnswers bot action.

  3. Answer: This is an entity node that accepts any string.

    1. Type: String
    2. User prompt: {{context.myService.response.body[context.currentQuestion]}}
      • This assumes the questions from your service are an array of strings. If they’re an array of objects instead, include the property that contains the question text: e.g., {{context.myService.response.body[context.currentQuestion].questionText}}.
  4. StoreAnswer: This runs after end of each question in your loop. It stores the answers in a temporary context variable. You could upload the answer to a web service at this point instead, depending on whether you need atomicity (i.e., only upload answers if user answers all questions).

    1. Put a script node inside it:

      context.answers.push(context.entities.Answer);
      delete context.entities.Answer;
      
    2. Set its default connection to go back to NextQuestion.

  5. UploadAnswers: This uploads the user’s answers to your service.

    1. Put a service node inside it.
      1. Set the HTTP verb to POST.

      2. Set the content type to application/json.

      3. Include {{context.answers}} somewhere in the body. Example: