0

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;
 };
asked Apr 25, 2020 at 0:59
1
  • 1
    you can't like that ... firstly, you need to return the Promise returned by fetch (you currently return undefined since there's no return from fetchJob), then to access the data you need to use .then where you call fetchJob Commented Apr 25, 2020 at 1:00

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Oscar! Async worked! ``` async function getResponseWithAsyncAwait() { const job = await fetchJob(data[k].employer); } ```

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.