简体   繁体   English

JavaScript 从 function 返回 promise

[英]JavaScript return promise from function

I'm trying to return data from a called function that has a promise in it.我正在尝试从名为 function 的数据中返回数据,其中包含 promise。 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;
    };

You can get the promise value with async/await or with Promises, bellow I do an example with this two techniques:您可以使用 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;
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM