我有一个功能来调用谷歌语音API。看起来一切都很好,但我找不到为什么它给我错误。我是节点和承诺的初学者所以不确定为什么会出现这个错误。
ReferenceError:在index.js中未定义resolve:57
问题在于代码的这一部分:
return speech
.longRunningRecognize(responses)
.then(function(results) {
var operation = responses[0];
console.log("Operation: ", operation);
return operation.promise();
})
.then(function(responses) {
resolve(responses[0]);
console.log("Result: ", JSON.stringify(responses[0]));
})
承诺
operation.promise()(第57行)
无法解决。它想要解决 承诺,但它看起来无法找到解决功能。
google api的工作原理如下:
我感觉它一切正常,呼叫已经完成,响应又回来了。代码等待,然后它想要解决,但它不能......
我的代码就像这样(它是一个云函数)
exports.transcribeAudio = functions.storage.object().onChange(event => {
const object = event.data;
const filePath = object.name;
const fileName = filePath.split("/").pop();
const fileBucket = object.bucket;
const bucket = gcs.bucket(fileBucket);
const tempFilePath = path.join(os.tmpdir(), fileName);
// Exit if this is triggered on a file that is not an image.
// Get the file name.
//const fileName = path.basename(filePath);
console.log(filePath + " name: " + fileName);
// Exit if the image is already a thumbnail.
if (!filePath.startsWith("ucl-flac-audio")) {
console.log("Only flac-audio need to be converted");
return true;
}
// Exit if this is a move or deletion event.
if (object.resourceState === "not_exists") {
console.log("This is a deletion event.");
return true;
}
return Promise.resolve()
.then(() => {
const audioFilename = "gs://" + fileBucket + "/" + filePath;
console.log(audioFilename);
const request = {
config: {
encoding: "FLAC",
languageCode: "fr-FR"
},
audio: {
uri: audioFilename
}
};
return speech
.longRunningRecognize(request)
.then(function(responses) {
var operation = responses[0];
console.log("Operation: ", operation);
return operation.promise();
})
.then(function(responses) {
resolve(responses[0]);
console.log("Result: ", JSON.stringify(responses[0]));
})
.catch(function(err) {
console.error("Failed to get transcript.", err);
// reject(err);
});
})
.catch(err => {
return Promise.reject(err);
});
});
答案 0 :(得分:12)
您不能在resolve()
处理程序中调用.then()
。那里没有定义这样的功能。如果要在.then()
处理程序中设置promise的已解析值,则可以返回该值。
改变这个:
.then(function(responses) {
resolve(responses[0]);
console.log("Result: ", JSON.stringify(responses[0]));
})
到此:
.then(function(responses) {
console.log("Result: ", JSON.stringify(responses[0]));
return responses[0];
})
仅供参考,你可能想到的resolve()
是新Promise执行者回调的参数:
let p = new Promise(function(resolve, reject) {
resolve(10);
});
而且,这是您使用它的上下文。
答案 1 :(得分:1)
在使用 resolve
之前,您需要将 resolve
作为参数传递:
在这种情况下,
return new Promise((resolve, reject) => {
axios.post('YOUR URL HERE', params)
.then(response => {
resolve() // Here you can use resolve as it passed as argument
})
});
注意:axios调用可以使用GET、POST