JavaScript从函数返回承诺

时间:2020-04-25 00:59:22

标签: javascript function promise return

我正在尝试从其中包含一个承诺的调用函数返回数据。如何将数据放入变量?

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 个答案:

答案 0 :(得分:1)

您可以使用async / await或Promises获取Promise值,下面我用这两种技术做一个例子:

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