我在课堂上拥有三种带有承诺的方法。而且我需要在getTranslate中使用setNewJsonAndGetTranslate方法的返回值,但不会返回任何内容
getTranslate(key) {
return this.setNewJsonAndGetTranslate(key); //<-- I get undefined, because nothing returned from Promise
}
setNewJsonAndGetTranslate(key) {
this.setJson().then(json => {
let translate = TranslateService.jsonPathToValue(json, key);
let result = JSON.stringify(translate[this.user.getLangCode()]);
if (result !== undefined) {
return result.substring(1, result.length - 1); //<-- I'm need to return this
} else {
return key;
}
});
}
setJson() {
return new Promise((resolve, reject) => {
$.getJSON(Environment.prefixPath + "assets/i18n.json", json => {
let translate = JSON.stringify(json);
window.localStorage.setItem("translate_json", translate);
resolve(json);
});
});
}
答案 0 :(得分:3)
这是因为您没有从setNewJsonAndTranslate
返回任何内容。 return
异步调用:
return this.setJson().then(json => {...});
您还可以使用async
函数和await
异步代码:
async setNewJsonAndGetTranslate(key) {
let json = await this.setJson();
let translate = TranslateService.jsonPathToValue(json, key);
let result = JSON.stringify(translate[this.user.getLangCode()]);
if (result !== undefined) {
return result.substring(1, result.length - 1); //<-- I'm need to return this
} else {
return key;
}
}