代码和您对代码的理解存在一些问题...
-
data 不是承诺返回的日期。 这是承诺。您只能在 promise 解决时获取 promise 的数据。在这种情况下,promise的数据实际上是x
- 使用
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
});
}
希望这会有所帮助...