RUS*_*HAH 5 javascript node.js google-cloud-functions dialogflow-es dialogflow-es-fulfillment
我收到错误,因为“异步函数”仅在 es8 中可用(使用“esversion 8”)” 我尝试在内联代码 package.json 中放入“esversion:8”,但它不起作用,并且函数未部署。
代码: index.js
'use strict';
'use esversion: 8'; //not working
async function getWeather() {
const city = 'Mumbai';
const OPENWEATHER_API_KEY = '<API KEY>';
const response = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${OPENWEATHER_API_KEY}`);
const data = await response.json();
console.log(data);
const { main } = data;
const { temp } = main;
const kelvin = temp;
const celsius = Math.round(kelvin - 273.15);
console.log(celsius);
}
Run Code Online (Sandbox Code Playgroud)
代码package.json
{
"name": "dialogflowFirebaseFulfillment",
"description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "8"
},
"scripts": {
"start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
"deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
},
"dependencies": {
"actions-on-google": "^2.2.0",
"firebase-admin": "^5.13.1",
"firebase-functions": "^2.0.2",
"dialogflow": "^0.6.0",
"dialogflow-fulfillment": "^0.5.0",
"esversion":"8" //not working
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法解决这个问题或者有其他方法吗?
您可以将函数从 async/await 转换为基于 Promise 的函数,您可以将函数体包装在 Promise 中,并使用 .then() 和 .catch() 分别处理已解决和已拒绝状态。
function getWeather() {
return new Promise((resolve, reject) => {
const city = 'Mumbai';
const OPENWEATHER_API_KEY = '<API KEY>';
fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${OPENWEATHER_API_KEY}`)
.then(response => response.json())
.then(data => {
console.log(data);
const { main } = data;
const { temp } = main;
const kelvin = temp;
const celsius = Math.round(kelvin - 273.15);
console.log(celsius);
resolve(celsius); // Resolve the Promise with the celsius value.
})
.catch(error => {
console.error(error);
reject(error); // Reject the Promise with the error if any occurs.
});
});
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样使用它:
function WeatherInfoMessage(agent){
return getWeather(agent)
.then(celsius => {
// Use the celsius value here when the Promise is resolved.
})
.catch(error => {
// Handle the error here when the Promise is rejected.
});
}
Run Code Online (Sandbox Code Playgroud)
然后,将意图映射设置为 WeatherInfoMessage()
intentMap.set('get weather', WeatherInfoMessage);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2707 次 |
| 最近记录: |