下面是我的代码我试图将我的文本翻译成德语并在翻译后分配给变量但是我得到空字符串你能帮助我并告诉我在执行下面的代码时我犯了什么错误。
如果错误,请为我的代码编码,并为我提供更正解决方案,以便在执行后translateString的结果应为“Hallo ich liebe deutsche Sprache”
我想在translate函数之外使用translatedString,以便结果是全局
// working with string translation
const translate = require('google-translate-api');
var myString = "Hello I love German language";
console.log("My String is "+ myString);
// result is My String is Hello I love German language
var translatedString = translate(myString, {to: 'de'})
.then(res => {translatedString = res.text});
console.log("Translated String is "+ JSON.stringify(translatedString));
// result is Translated String is {}
// expected result is Translated String is Hallo ich liebe deutsche Sprache
答案 0 :(得分:3)
翻译正在回复一个承诺。 promise表示最终值;翻译将无法立即提供。如果您想与最终价值进行互动,则需要将代码放入承诺的.then
方法中。
const translate = require('google-translate-api');
let myString = "Hello I love German language";
console.log("My String is "+ myString);
let promise = translate(myString, {to: 'de'}).then(res => {
return res.text;
});
promise.then(translatedString => {
console.log("Translated String is "+ JSON.stringify(translatedString));
});
console.log('The translation has started, but it isn\'t ready yet');
编辑:根据要求,这是一个将其保存到变量的版本。这不是我的建议:
const translate = require('google-translate-api');
let myString = "Hello I love German language";
console.log("My String is "+ myString);
let translatedString = null;
let promise = translate(myString, {to: 'de'}).then(res => {
translatedString = res.text;
});
promise.then(() => {
console.log("Translated String is "+ JSON.stringify(translatedString));
});
答案 1 :(得分:0)
因为您在接收结果之前记录变量,而在解析承诺时应记录它:
translate(myString, {to: 'de'}).then(res => {
console.log(res.text); //Hallo ich liebe deutsche Sprache
});
答案 2 :(得分:0)
最后一次console.log()
电话在Promise
链之外。您可以使.then()
return
Promise
值.then()
链接到Promise
链中的下一个async/await
或Promise
以获取{{1}的值在async
函数
const translatePhrase = async(myString) => {
const translate = require('google-translate-api');
// working with string translation
console.log("My String is "+ myString);
// result is My String is Hello I love German language
const translatedString = await translate(myString, {to: 'de'}).then(res => res.text);
console.log("Translated String is "+ JSON.stringify(translatedString));
}
translatePhrase("Hello I love German language");