我正在将next.js与库https://github.com/auth0/nextjs-auth0/一起使用
要初始化该库,我需要使用async / await从保险柜中获取一个秘密,但是我得到了Promise { <pending> }
我认为以下方法会起作用:
// utils/auth0.js
import { initAuth0 } from '@auth0/nextjs-auth0';
const vault = require('./vault');
async function getSecretFromVault() {
const res = await vault.fetchSecret();
console.log(res); // shows my secret correctly
return res;
}
const secret = getSecretFromVault();
console.log(secret); // shows Promise { <pending> }
export default initAuth0({
clientId: "my_ID",
clientSecret: secret // this will be invalid: UI shows "client_id is required"
....
});
正确的方法是什么?
答案 0 :(得分:1)
async
方法返回一个承诺,您应该使用await
来获取异步数据。
由于模块导出是 sync ,因此最好导出 async 方法,该方法将使您对Vault进行调用并返回Auth0的初始化。
// utils/auth0.js
import { initAuth0 } from '@auth0/nextjs-auth0';
const vault = require('./vault');
async function getSecretFromVault() {
const res = await vault.fetchSecret();
console.log(res); // shows my secret correctly
return res;
}
let instance;
async function getAuth0() {
if(instance) {
return Promise.resolve(instance);
}
const secret = await getSecretFromVault();
// -------------^
instance = initAuth0({
clientId: 'my_ID',
clientSecret: secret, // this will be invalid: UI shows "client_id is required"
});
return instance;
}
export default getAuth0;
// usage
import getAuth0 from './utils/auth0';
export default async function login(req, res) {
const auth0 = await getAuth0();
// --------------------^ get instance
try {
await auth0.handleLogin(req, res);
} catch (error) {
console.error(error);
res.status(error.status || 400).end(error.message);
}
}