【问题标题】:Return function result with "throw" is this correct way to use throw?使用“throw”返回函数结果是使用 throw 的正确方法吗?
【发布时间】:2020-02-05 10:34:42
【问题描述】:

我的一个同事给我发了这个代码块:

export const getFieldChoice = (key, listName, fieldName) => {
  const value = cache.get(key) || { status: "new", data: null }

  if (value.status === "resolved") {
    return value.data
  }
  const data = spApi.lists.getByTitle(listName).fields.getByInternalNameOrTitle(fieldName).select('Choices').get().then(x => {
    value.data = x
    value.status = "resolved"
    cache.set(key, value)
  })
  throw data
}

然后我看到他用throw返回了promise数据。这是使用throw的正确方法吗?

【问题讨论】:

  • "这是使用 throw 的正确方法吗?"不,不是。

标签: javascript throw


【解决方案1】:

代码和您对代码的理解存在一些问题...

  1. data 不是承诺返回的日期。 这是承诺。您只能在 promise 解决时获取 promise 的数据。在这种情况下,promise的数据实际上是x
  2. 使用throw 关键字总是会导致异常,如果不处理,则会导致错误。在这种情况下,函数总是会抛出异常,所以我不确定这里的目标是什么。

要在此函数中实际获取 Promise 的值,有两种方法。你要么await 承诺,要么提供一个回调函数在承诺解决时调用......

异步/等待方法

export const getFieldChoice = async (key, listName, fieldName) => {
  const value = cache.get(key) || { status: "new", data: null }
  if (value.status === "resolved") return value.data;

  const data = await spApi.lists.getByTitle(listName).fields.getByInternalNameOrTitle(fieldName).select('Choices').get();

  value.data = data;
  value.status = "resolved"
  cache.set(key, value)

  return value;
}

然后就这样使用

import { getFieldChoice } from "path/to/file";

async function caller () {
  try {
    const key = "key";
    const listName = "list name";
    const fieldName = "field name";

    const data = await getFieldChoice(key, listName, fieldName);
    // Rest of function logic
  } catch (err) {
    // Handle any error
  }
}

回调方法

export const getFieldChoice = (key, listName, fieldName, callback) => {
  const value = cache.get(key) || { status: "new", data: null }
  if (value.status === "resolved") return value.data;


 spApi.lists.getByTitle(listName).fields.getByInternalNameOrTitle(fieldName).select('Choices').get().then(data => {
    value.data = data;
    value.status = "resolved"
    cache.set(key, value)

    callback(null, value);
  }).catch(err => {
    callback(err);
  });
}

然后就这样使用

import { getFieldChoice } from "path/to/file";

function caller () {
  const key = "key";
  const listName = "list name";
  const fieldName = "field name";

  getFieldChoice(key, listName, fieldName, (err, value) => {
    if (err) {
      // Handle any error
    }

    // Rest of function logic
  });

}

希望这会有所帮助...

【讨论】:

  • 感谢您的详细解答。我知道 Promise 是如何工作的,以及如何使用 then() 或 async/await 从 Promise 中检索数据。事情就在这里,上面的代码抛出了承诺,而不是返回承诺。我问那可以兑现承诺吗?你说这是错误的, throw 关键字总是会导致异常,它回答了我的问题。谢谢你:)
猜你喜欢
  • 1970-01-01
  • 2016-03-15
  • 2021-01-16
  • 2017-07-31
  • 1970-01-01
  • 2016-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多