简体   繁体   English

为什么我在这个函数上未定义?

[英]why am I getting undefined on this function?

I'm building a dialogflow agent that uses Airtable as database (library: airtable js)我正在构建一个使用 Airtable 作为数据库的 dialogflow 代理(库:airtable js)

Everything works fine except I can't get the value "out of" the function in order to send it back to the dialogflow agent.一切正常,除了我无法从函数中“取出”值以将其发送回对话流代理。

Function功能

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(tablePlaces)
      .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); //this works fine

          finalPrice = arraySinglePrice[0].price; //this works fine

          return finalPrice;
        }
      });   
   
    agent.add(`I wanted to get the result in here: ${finalPrice}`); //undefined
  }

I'm new to asynchronous programming, so I'm probably messing up with the Airtable js promises, but can't figure it out how to get it to work.我是异步编程的新手,所以我可能搞砸了 Airtable js 的承诺,但不知道如何让它工作。

Would appreciate any help将不胜感激任何帮助

EDIT编辑

THANKS @PRISONER FOR THE HELP.感谢@PRISONER 的帮助。

FOR THOSE IN NEED, HERE IS THE WORKING CODE:对于有需要的人,这是工作代码:

function showSinglePrice(agent) {    

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

    return base(tablePlaces) //defined variable before this function
      .select({
        maxRecords: 1, //just want 1
        view: viewName, //defined variable before this function
        filterByFormula: `AND({type} = "${type}",{size} = "${size}",{place} = "${place}")`
      })
      .firstPage()
      .then(result => {
        
        console.log(result);

        var getPrice = result[0].fields.price;

        agent.add(`the current price is: $ ${getPrice}`); //its working
      })
      .catch(error => {
        console.log(error);

        response.json({
          fulfillmentMessages: [
            {
              text: {
                text: ["We got the following error..."] //will work on it
              }
            }
          ]
        });
      });
  }

You're correct, there are some issues with how you're using Promises.您是对的,您使用 Promise 的方式存在一些问题。 You're using a callback function in your call to firstPage() instead of having it return a Promise.您在调用firstPage()使用了回调函数,而不是让它返回 Promise。 So you could have written that part to look something like this:所以你可以把那部分写成这样:

  .firstPage()
  .then( records => {
    // Work with the records here
  })
  .catch( err => {
    // Deal with the error
  });

Once you're dealing with Promises, everything you want to do must be done inside the .then() block.一旦你处理了 Promises,你想做的一切都必须在.then()块中完成。 So you'll need to move the agent.add() in there.所以你需要将agent.add()移到那里。

You also need to return the Promise, so Dialogflow knows that theres an asynchronous operation taking place.需要返回 Promise,以便 Dialogflow 知道发生了异步操作。 Since the .then() and .catch() functions return a Promise, you can just return the result of the whole expression.由于.catch() .then().catch()函数返回一个 Promise,你可以只返回整个表达式的结果。 So something like所以像

  return base(tablePlaces)
      .select(query)
      .firstPage()
      .then(/*function*/)
      .catch(/*function*/);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM