How to return the value of Promis?

It is possible of the promis to return a variable and use elsewhere?
func1() {
 this.setJson().then(json => {
 return json;
});
}

 func2() {
 let q = this.func1();
 return q;
 }
March 23rd 20 at 19:07
2 answers
March 23rd 20 at 19:09
func1() {
 return this.setJson();
}

async func2() {
 let q = await this.func1();
 return q;
}
Maybe he wanted to use in the first function value, then it will be so
const root = 'https://jsonplaceholder.typicode.com';
const func1 = function() {
 return fetch(root + '/posts/2').then(response => {
 if (response.status === 200) {
 return response.json();
 } else {
 throw new Error("API error")
}
 }).then((json) => {
console.log("2",json);
 json.fetched = new Date();
 return json;
})
}
const func2 = async function() {
 let q = await func1();
 console.log("1", q)
 return q;
}
func2();
- laurel commented on March 23rd 20 at 19:12
In my class there are three methods and I can't figure out how to getTranslate get the value from the setNewJsonAndGetTranslate

getTranslate(key) {
 return this.setNewJsonAndGetTranslate(key); <--undefined
}

 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); <-- need to return
 } 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);
});
});
 }
- vance.Paucek94 commented on March 23rd 20 at 19:15
@vance.Paucek94, promis - asynchronous thing, you can't work synchronously
Output number 1 to make getTranslate asynchronous and inside it to get the value using await (look carefully at the code @maybelle76 ) and add a return before this.setJson(). in this case, to work with the method getTranslate you're like a promis
2) Just returned from setNewJsonAndGetTranslate getTranslate and work with her as promisor - laurel commented on March 23rd 20 at 19:18
@laurel, it turns out a vicious circle. Tried so
async getTranslate(key) {
 return await this.setNewJsonAndGetTranslate(key);
 }


in the end, console get getTranslate = Promise {}, which I still can't use as I need - vance.Paucek94 commented on March 23rd 20 at 19:21
@vance.Paucek94, Read the article below three times
If you want to work with promises in a linear way, you always have to use await, or after then - laurel commented on March 23rd 20 at 19:24
March 23rd 20 at 19:11

Find more questions by tags JavaScript