【问题标题】:JavaScript return promise from functionJavaScript从函数返回promise
【发布时间】:2020-04-25 00:59:22
【问题描述】:

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

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

【问题讨论】:

  • 你不能喜欢这样......首先,你需要返回 fetch 返回的 Promise(你当前返回 undefined,因为 fetchJob 没有返回),然后访问你需要使用的数据.然后你打电话给fetchJob

标签: javascript function promise return


【解决方案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;
  });
}

【讨论】:

  • 感谢@Oscar!异步工作! ``` 异步函数 getResponseWithAsyncAwait() { const job = await fetchJob(data[k].employer); } ```
猜你喜欢
  • 1970-01-01
  • 2022-11-14
  • 2022-01-10
  • 1970-01-01
  • 2019-12-14
  • 2019-10-23
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多