Why am I getting Undefined on the return of this function?

Asked

Viewed 42 times

-1

I’m creating an agent in Dialogflow and using Airtable as BD.

Everything is working well, I’m able to access the comic and bring the results.

But I can’t "throw the result out" of the function and access it at the end to print.

Follows code:

function showSinglePrice(agent) {
    var finalPrice;
    var arraySinglePrice = null;

    const item = agent.context.get("item"),
      place = item.parameters.place,
      size = item.parameters.size,
      type = item.parameters.type;

    base(tablePizzas)
      .select({
        maxRecords: 10, //
        view: viewName,
        filterByFormula: `AND({type} = "${type}",{size} = "${size}",{place} = "${place}")` 
      })
      .firstPage(function(error, records) {
        if (error) {
          response.send({ error: error });
        } else {
          arraySinglePrice = records.map(record => {
            return {
              price: record.get("price")
            };
          });

          console.log(arraySinglePrice); //isso funfa

          var finalPrice = arraySinglePrice[0].price; //isso tb

          return finalPrice;
        }
      });   
   
    agent.add(`Valor deveria vir aqui: ${finalPrice}`); //não chega aqui

  }

Always gives Undefined.

I’ve tried a lot of things, but I’m stuck.

Some help?

2 answers

0

I believe it’s because you defined the variable finalPrice 2 times. Once at the beginning, and a second time before Return. In the case of the second time you should do without the var, only by assigning the value to the variable: finalPrice = arraySinglePrice[0].price;.

I don’t know if that’s it, keep us updated.

  • your remark is correct. thanks for pointing. fixed now. Still the problem persists. The method I am using . select(). firstpage() comes from a library called airtable.js| This method returns a precedent. So I know in theory that the JS is "advancing", trying to print at the end before the method ends. But I don’t know how to do the STOP code, wait for the end of the call before.

0

When you give the return finalPrice; it exits the function by not executing the agent.add(Valor deveria vir aqui: ${finalPrice});, tries to add the agent.add() before the return

Browser other questions tagged

You are not signed in. Login or sign up in order to post.