[英]why am I getting undefined on this function?
我正在構建一個使用 Airtable 作為數據庫的 dialogflow 代理(庫:airtable js)
一切正常,除了我無法從函數中“取出”值以將其發送回對話流代理。
功能
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
}
我是異步編程的新手,所以我可能搞砸了 Airtable js 的承諾,但不知道如何讓它工作。
將不勝感激任何幫助
編輯
感謝@PRISONER 的幫助。
對於有需要的人,這是工作代碼:
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
}
}
]
});
});
}
您是對的,您使用 Promise 的方式存在一些問題。 您在調用firstPage()
使用了回調函數,而不是讓它返回 Promise。 所以你可以把那部分寫成這樣:
.firstPage()
.then( records => {
// Work with the records here
})
.catch( err => {
// Deal with the error
});
一旦你處理了 Promises,你想做的一切都必須在.then()
塊中完成。 所以你需要將agent.add()
移到那里。
您還需要返回 Promise,以便 Dialogflow 知道發生了異步操作。 由於.catch()
.then()
和.catch()
函數返回一個 Promise,你可以只返回整個表達式的結果。 所以像
return base(tablePlaces)
.select(query)
.firstPage()
.then(/*function*/)
.catch(/*function*/);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.