Ошибка синтаксиса: ожидание действительно только в функции asyn c в Google Cloud Speech-to-Text - PullRequest
0 голосов
/ 27 февраля 2020

Любитель как в node.js, так и в облачных инструментах Google. Я взял этот код, чтобы попытаться транскрибировать фрагмент аудио из моего сегмента Google Cloud. Когда я запускаю node index.js в терминале, я просто получаю SyntaxError: await действует только в asyn c function . Я понимаю, что это означает, что мне нужна функция asyn c. Но как я могу превратить весь этот файл в команду, которую можно успешно запустить из терминала?

// 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}`);

Ответы [ 2 ]

0 голосов
/ 27 февраля 2020

Вы не можете написать await operation.promise() вне функции asyn c. Если вы хотите использовать 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>, чтобы запустить его.

0 голосов
/ 27 февраля 2020

Просто поместите в asyn c функцию:

// earlier code here

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

main()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...