我正在尝试创建一个单例服务类,在该类中我实例化一个连接到后端的连接对象,以便在每个组件中重用该连接对象,因此我做到了:
const {
Kuzzle,
WebSocket
} = require('kuzzle-sdk');
class KuzzleService {
static instance = null;
static async createInstance() {
var object = new KuzzleService();
object.kuzzle = new Kuzzle(
new WebSocket('localhost'),{defaultIndex: 'index'}
);
await object.kuzzle.connect();
const credentials = { username: 'user', password: 'pass' };
const jwt = await object.kuzzle.auth.login('local', credentials);
return object;
}
static async getInstance () {
if (!KuzzleService.instance) {
KuzzleService.instance = await KuzzleService.createInstance();
}
return KuzzleService.instance;
}
}
const kuzzleService = KuzzleService.getInstance();
export default kuzzleService;
但是当我将服务导入组件时,如下所示:
import kuzzleService from "../services/kuzzle-service.js";
我打印出来:
async componentDidMount(){
console.log(JSON.stringify(kuzzleService.kuzzle));
}
它给我“未定义”。我应该以其他方式导入服务吗?
答案 0 :(得分:2)
这可能是因为当您导出kuzzleService
时,.getInstance()
给出的承诺尚未解决。
您应该导出.getInstance
函数,并在componentDidMount
中等待它,如下所示:
export default KuzzleService; // export the singleton directly
async componentDidMount(){
const kuzzle = await KuzzleService.getInstance();
console.log(kuzzle);
}