使用 "crypto" 创建的函数不会 return 我用它创建的 bearerToken
Function created using "crypto" won't return the bearerToken I created with it
我确信这是我所缺少的基本知识,但已经晚了,我的大脑已经变成那样了。所以我有这个功能:
export const createRandomHex = () => {
try {
return crypto.randomBytes(127, (_err, buf) => {
console.log("[create] bearerToken: ", buf.toString("hex"));
const bearerTokenString = buf.toString("hex");
return bearerTokenString;
});
} catch (e) {
return e;
}
};
我在另一个函数中这样调用它:
export const createBearerToken = () => {
const bearerToken = createRandomHex();
}
由于某种原因,createBearerToken 中的 bearerToken 值未定义或为空。谁能帮我解决这个问题?
randomBytes
是异步的,需要回调。您可以 return 在您的函数中承诺:
export const createRandomHex = async () => {
return new Promise((resolve, reject) => {
try {
return crypto.randomBytes(127, (_err, buf) => {
console.log("[create] bearerToken: ", buf.toString("hex"));
const bearerTokenString = buf.toString("hex");
resolve(bearerTokenString);
});
} catch (e) {
reject(e);
}
});
};
我确信这是我所缺少的基本知识,但已经晚了,我的大脑已经变成那样了。所以我有这个功能:
export const createRandomHex = () => {
try {
return crypto.randomBytes(127, (_err, buf) => {
console.log("[create] bearerToken: ", buf.toString("hex"));
const bearerTokenString = buf.toString("hex");
return bearerTokenString;
});
} catch (e) {
return e;
}
};
我在另一个函数中这样调用它:
export const createBearerToken = () => {
const bearerToken = createRandomHex();
}
由于某种原因,createBearerToken 中的 bearerToken 值未定义或为空。谁能帮我解决这个问题?
randomBytes
是异步的,需要回调。您可以 return 在您的函数中承诺:
export const createRandomHex = async () => {
return new Promise((resolve, reject) => {
try {
return crypto.randomBytes(127, (_err, buf) => {
console.log("[create] bearerToken: ", buf.toString("hex"));
const bearerTokenString = buf.toString("hex");
resolve(bearerTokenString);
});
} catch (e) {
reject(e);
}
});
};