首页 > 解决方案 > SyntaxError:await 仅在 Google Cloud Speech-to-Text 的异步函数中有效

问题描述

在 node.js 和谷歌云工具方面有点业余。我已使用此代码尝试从我的 Google Cloud 存储桶中转录一段音频。当我node index.js在终端中运行时,我只会得到SyntaxError: await is only valid in async function。我意识到这意味着我需要一个异步函数。但是我怎样才能把整个文件变成一个可以从终端成功运行的命令呢?

// Imports the Google Cloud client library
const speech = require('@google-cloud/speech');

// Creates a client
const client = new speech.SpeechClient();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
const gcsUri = 'gs://anitomaudiofiles/911isnojoke.mp3';
const encoding = 'MP3';
const sampleRateHertz = 16000;
const languageCode = 'en-US';

const config = {
  encoding: encoding,
  sampleRateHertz: sampleRateHertz,
  languageCode: languageCode,
};

const audio = {
  uri: gcsUri,
};

const request = {
  config: config,
  audio: audio,
};

// Detects speech in the audio file. This creates a recognition job that you
// can wait for now, or get its result later.
const [operation] = await client.longRunningRecognize(request);
// Get a Promise representation of the final result of the job
const [response] = await operation.promise();
const transcription = response.results
  .map(result => result.alternatives[0].transcript)
  .join('\n');
console.log(`Transcription: ${transcription}`);

标签: node.jsterminal

解决方案


您不能await operation.promise()在异步函数之外编写。如果你想使用 await 它应该在一个函数中。

(async runOperations() {
  const [operation] = await client.longRunningRecognize(request);
  // Get a Promise representation of the final result of the job

  const [response] = await operation.promise();
  const transcription = response.results
      .map(result => result.alternatives[0].transcript)
      .join('\n');
  console.log(`Transcription: ${transcription}`);
})();

您可以将其放入文件中并运行node <filename.js>以运行它。


推荐阅读