I'm trying to return data from a called function that has a promise in it. How do I get the data into the variable?
var job = fetchJob(data[k].employer);
function fetchJob(name) {
var test = 'null'
fetch(`https://${ GetParentResourceName() }/jsfour-computer:policeFetchJob`, {
method: 'POST',
body: JSON.stringify({
type: 'policeFetchJob',
data: {
'@name': name,
}
})
})
.then( response => response.json() )
.then( data => {
if ( data != 'false' && data.length > 0 ) {
return data
})
return null;
};
1 Answer 1
You can get the promise value with async/await or with Promises, bellow I do an example with this two techniques:
function fetchJob(name) {
return fetch(`https://${GetParentResourceName()}/jsfour-computer:policeFetchJob`, {
method: "POST",
body: JSON.stringify({
type: "policeFetchJob",
data: {
"@name": name,
},
}),
})
.then((response) => response.json())
.then((data) => {
if (data != "false" && data.length > 0) {
return data;
}
});
}
async function getResponseWithAsyncAwait() {
const job = await fetchJob(data[k].employer);
}
function getResponseWithPromises() {
fetchJob(data[k].employer).then((data) => {
const job = data;
});
}
answered Apr 25, 2020 at 1:21
Oscar Velandia
1,1661 gold badge8 silver badges10 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Erik Meyer
Thanks @Oscar! Async worked! ``` async function getResponseWithAsyncAwait() { const job = await fetchJob(data[k].employer); } ```
lang-js
fetchJob