NodeJS 如何在对话流中使用异步函数?

fzsnzjdm  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(75)

我得到的错误是**“async functions' is only available in es8(use 'esversion 8')"我尝试将“esversion:8”*放入内联代码package.json中,但它不起作用,函数也没有部署。
编码:
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);
   }

字符串
代码 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
  }
}


Error Screenshot
有没有解决这个问题的办法或其他方法?

j8ag8udp

j8ag8udp1#

你可以将函数从async/await转换为基于Promise的函数,你可以将函数体 Package 在Promise中,并使用.then()和.catch()分别处理resolved和rejected状态。

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.
      });
  });
}

字符串
你可以这样使用它:

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.
          });      
  }


然后,将IntentMap设置为WeatherInfoMessage()

intentMap.set('get weather', WeatherInfoMessage);

相关问题