带有promisify的节点回调样式? “'原始'自变量必须是函数类型”

时间:2019-02-12 15:53:08

标签: javascript node.js callback es6-promise

我正在Google Cloud Function中使用util.promisify来调用IBM Watson Text-to-Speech,它返回一个回调。我的代码有效,但收到错误消息:

TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type function

documentation

  

采用遵循常见错误优先回调样式的函数,即   将(err, value) => ...回调作为最后一个参数,并且   返回一个返回承诺的版本。

IBM Watson回调很复杂,我不知道如何将其重构为Node.js回调样式。它正在工作,我应该忽略该错误消息吗?这是我的Google Cloud Function:

exports.IBM_T2S = functions.firestore.document('Users/{userID}/Spanish/IBM_T2S_Request').onUpdate((change) => {

    let word = change.after.data().word;
    let wordFileType = word + '.mp3';

    function getIBMT2S(word, wordFileType) {
      const {Storage} = require('@google-cloud/storage');
      const storage = new Storage();
      const bucket = storage.bucket('myProject.appspot.com');
      const file = bucket.file('Audio/Spanish/Latin_America/' + wordFileType);
      var util = require('util');
      var TextToSpeechV1 = require('watson-developer-cloud/text-to-speech/v1');

      var textToSpeech = new TextToSpeechV1({
        username: 'groucho',
        password: 'swordfish',
        url: 'https://stream.watsonplatform.net/text-to-speech/api'
      });

      var synthesizeParams = {
        text: word,
        accept: 'audio/mpeg',
        voice: 'es-LA_SofiaVoice',
      };

      const options = { // construct the file to write
        metadata: {
          contentType: 'audio/mpeg',
          metadata: {
            source: 'IBM Watson Text-to-Speech',
            languageCode: 'es-LA',
            gender: 'Female'
          }
        }
      };

      textToSpeech.synthesize(synthesizeParams).on('error', function(error) {
        console.log(error);
      }).pipe(file.createWriteStream(options))
      .on('error', function(error) {
        console.error(error);
      })
      .on('finish', function() {
        console.log("Audio file written to Storage.");
      });
    };

var passGetIBMT2S = util.promisify(getIBMT2S(word, wordFileType))
passGetIBMT2S(word, wordFileType)
});

2 个答案:

答案 0 :(得分:3)

之所以起作用,是因为您正在调用HOST_WRITE并将返回值传递给getIBMT2S而不是函数本身。

这里有几个问题,首先,您的util.promisfy函数似乎与getIBMT2S不兼容,正如您从文档中突出显示的那样,兼容函数应遵循典型的回调样式签名(util.promisfy不使用回调参数)。

第二,getIBMT2S期望一个util.promisify-在您的情况下,您传递的是函数的 return 值。如果function已更新为支持回调参数,则正确用法为

getIBMT2S

答案 1 :(得分:0)

这是我完成的代码。有两个功能。 getT2S调用IBM Watson Text-to-Speech,然后将音频文件写入Storage,然后获取下载URL。 writeDownloadURL检查是否存在Firestore文档,然后setsupdates下载Firestore的下载URL。

exports.IBM_T2S = functions.firestore.document('Users/{userID}/Spanish/IBM_T2S_Request').onUpdate((change) => {

if (change.after.data().word != undefined) {
  // get requested word object
  let accent = change.after.data().accent;
  let audioType = change.after.data().audioType;
  let gender = change.after.data().gender;
  let longLanguage = change.after.data().longLanguage;
  let shortLanguage = change.after.data().shortLanguage;
  let shortSource = change.after.data().shortSource;
  let source = change.after.data().source;
  let voice = change.after.data().voice;
  let word = change.after.data().word;
  console.log(word);
  let wordFileType = word + '.' + audioType;
  let pronunciation = `${accent}-${gender}-${shortSource}`;

  const {Storage} = require('@google-cloud/storage');
  const storage = new Storage();
  const bucket = storage.bucket('myProject.appspot.com');
  const file = bucket.file('Audio/' + longLanguage + '/' + pronunciation + '/' + wordFileType);

  var TextToSpeechV1 = require('watson-developer-cloud/text-to-speech/v1');

  var textToSpeech = new TextToSpeechV1({
    username: 'groucho',
    password: 'swordfish',
    url: 'https://stream.watsonplatform.net/text-to-speech/api'
  });

  var synthesizeParams = {
    text: word,
    accept: 'audio/' + audioType,
    voice: voice
  };

  const options = { // construct the file to write
    metadata: {
      contentType: 'audio/' + audioType,
      metadata: {
        accent: accent,
        audioType: audioType,
        gender: gender,
        longLanguage: longLanguage,
        shortLanguage: shortLanguage,
        source: source,
        voice: voice,
        word: word
      }
    }
  };

  // check if Pronunciations collection exists, set or update to not destroy existing data
  function writeDownloadURL(downloadURL) {
    admin.firestore().collection('Dictionaries').doc(longLanguage).collection('Words').doc(word).collection('Pronunciations').doc(pronunciation).get()
    .then(function(doc) {
      if (doc.exists) {
        return admin.firestore().collection('Dictionaries').doc(longLanguage).collection('Words').doc(word).collection('Pronunciations').doc(pronunciation).update({ audioFile: downloadURL })
        .then(result => console.log('DONE'))
        .catch(error => console.error(error));
      } else {
        return admin.firestore().collection('Dictionaries').doc(longLanguage).collection('Words').doc(word).collection('Pronunciations').doc(pronunciation).set({ audioFile: downloadURL })
        .then(result => console.log('DONE'))
        .catch(error => console.error(error));
      } // close else
    })
    .catch(error => console.error(error));
  } // close writeDownloadURL

  // documentation at https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises
  function getT2S(synthesizeParams) {
    return new Promise(function(resolve, reject) {
      // documentation at https://cloud.ibm.com/apidocs/text-to-speech?code=node#synthesize-audio-get
      textToSpeech.synthesize(synthesizeParams).on('error', function(error) {
        console.error(error);
        reject(error);
      }).pipe(file.createWriteStream(options))
      .on('error', function(error) {
        console.error(error);
        reject(error);
      })
      .on('finish', function() {
        resolve(file.getSignedUrl({
          action: 'read',
          expires: '03-17-2025'
        }));
      }); // close on finish
    }); // close Promise
  } // close getT2SAsync

  async function getT2SAsync(synthesizeParams) {
    var signedUrls = await getT2S(synthesizeParams);
    var downloadURL = signedUrls[0];
    await writeDownloadURL(downloadURL);
    console.log("All done.");
  }

  return getT2SAsync(synthesizeParams);

} else { // if no word passed to function
  console.error("Error.");
}
}); // close IBM_T2S

我写错了

 return file.getSignedUrl({

代替

 resolve(file.getSignedUrl({

结果是没有数据从诺言中返回,并且云功能在六秒后超时,而没有完成执行。您必须对resolve做些事情。我曾两次使用reject来确定。 :-)