Erik Meyer
Erik Meyer

Reputation: 33

JavaScript return promise from function

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;
    };

Upvotes: 0

Views: 213

Answers (1)

Oscar Velandia
Oscar Velandia

Reputation: 1166

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;
  });
}

Upvotes: 1

Related Questions