node.js - 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}`);
解决方案
您不能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>
以运行它。
推荐阅读
- c# - 在 ASP.NET MVC 控制器的单个方法中异步调用多个方法
- php - Google Cloud Storage - 存储桶名称无效 (PHP)
- php - 如何在 API 平台上使用“paramconverter”?
- java - 如何使用 geckodriver (in Java) 检索 Firefox 的崩溃数据
- c# - 当另一个人开始统一播放时取消声音
- php - 泊坞窗中的 Apache+php。无法访问 ENV 变量
- here-api - 重新路由中没有永久 ID(HERE Android Premium SDK)
- java - 是否有任何算法可以打印出来以用正方形控制数组?
- r - 如何在R中提取数据框的第一列和最后3列
- c# - 如何在 MVC 应用程序中使用单个上传控件上传多个文件