JavaScript вернуть обещание из функции - PullRequest
0 голосов
/ 25 апреля 2020

Я пытаюсь вернуть данные из вызываемой функции, в которой есть обещание. Как мне получить данные в переменную?

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 Ответ

1 голос
/ 25 апреля 2020

Вы можете получить значение обещания с помощью async / await или Promises, ниже я приведу пример с этими двумя методами:

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