如何解决为什么在此函数上未定义?
我正在构建一个使用Airtable作为数据库的对话流代理(库:airtable js)
一切正常,除了我无法从函数中获取值以将其发送回dialogflow代理之外。
功能
df["x"] = df["x"].astype(x_cat)
x_dummies = pd.get_dummies(df.x)
a b c d e
0 1 0 0 0 0
1 0 1 0 0 0
2 0 0 1 0 0
我是异步编程的新手,所以我很可能会搞砸Airtable js的承诺,但无法弄清楚如何使其工作。
非常感谢您的帮助
编辑
感谢@PRISONER的帮助。
出于需要,这是工作代码:
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
}
解决方法
您是正确的,您使用Promises的方式存在一些问题。您在对firstPage()
的调用中使用了回调函数,而不是让它返回Promise。因此,您可以编写该部分以使其看起来像这样:
.firstPage()
.then( records => {
// Work with the records here
})
.catch( err => {
// Deal with the error
});
一旦您处理了Promises,您想做的所有事情都必须在.then()
块内完成。因此,您需要将agent.add()
移动到那里。
您还还需要返回Promise,因此Dialogflow知道正在进行异步操作。由于.then()
和.catch()
函数返回一个Promise,因此您只需返回整个表达式的结果即可。所以像
return base(tablePlaces)
.select(query)
.firstPage()
.then(/*function*/)
.catch(/*function*/);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。