我的问题是,在 Dialogflow 中,我的意图调用了调用方法的 webhook。 当所有 console.logs 工作时,方法“CheckCosts”正在运行。 但是 webhook 没有从“CheckCosts”方法的输出中检索任何内容。
下面是网络钩子(Hook)。这是在提交意图时调用的 webhook。
function checkCostsIntent(app) {
let origin = parameter.originAddress;
let destination = parameter.destinationAddress;
let costString = '';
/*let testing = CheckCosts(origin, destination);
app.add(testing);*/
CheckCosts(origin, destination).then((cost)=>{
console.log(cost);
costString = cost;
});
app.add(costString);
}
下面是 webhook 将调用的方法。
function CheckCosts(originAddress, destinationAddress) {
return new Promise((resolve, reject) => {
let defaultPath = 'maps.googleapis.com/maps/api/distancematrix/json?units=metric';
let APIKey = '&key=<API KEY>';
let origin = originAddress;
let destination = destinationAddress;
let newPath = defaultPath + '&origins=' + origin + '&destinations=' + destination + APIKey;
let url = 'https://' + newPath;
console.log(url);
https.get(url, (res) => {
let body = '';
res.on('data', (d) => { body += d; }); // store each response chunk
res.on('end', () => {
let response = JSON.parse(body);
console.log(response);
let distance = response.rows[0].elements[0].distance.text;
let travelTime = response.rows[0].elements[0].duration.text;
let distanceValue = response.rows[0].elements[0].distance.value;
let travelTimeValue = response.rows[0].elements[0].duration.value;
var ref = database.ref().child('price');
return ref.once('value').then(function (snapshot) {
let baseFair = snapshot.child('base').val();
let perKm = snapshot.child('perKm').val();
let perMin = snapshot.child('perMin').val();
let distanceCost = distanceValue / 1000 * perKm;
let timeCosts = travelTimeValue / 60 * perMin;
let cost = baseFair + distanceCost + timeCosts;
cost = cost.toFixed(2);
console.log('Total costs of distance is $' + distanceCost);
console.log('Total costs of time is $' + timeCosts);
console.log('The total cost of the ride is $' + cost);
let output = 'Distance between ' + origin + ' and ' + destination + ' is ' + distance + '. Time taken is ' + travelTime + '. And the total cost of the ride is $' + cost;
console.log(output);
resolve(output);
},
function (error) {
console.log('error' + error.code);
});
});
response.on('error', (error) => {
console.log(`error calling the Distance Matrix API:' ${error}`);
reject('fail');
});
});
});
}
基本上主要的问题是我没有在我的 webhook 中得到 resolve(output)
因为我从我的 中的
网络钩子(Hook)。console.log()
什么也得不到checkCostsIntent()
我的返回 promise 有问题吗? 还是我的决心?
最佳答案
没关系。我只需要在我的代码前面添加“return”
return CheckCosts(origin, destination).then((cost)=>{
app.add(cost);
});
它有效
关于javascript - 在 Dialogflow 中返回 Promise 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58925565/