我在类组件中有三个带有 promise 的方法。我需要在 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);
});
});
}
最佳答案
这是因为您没有从 setNewJsonAndTranslate
返回任何内容。 返回
异步调用:
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;
}
}
关于javascript - 如何从 Promise 返回值并在另一个方法中使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56458401/