问题

我正在尝试创建一个单例服务类,其中我instanciate连接到后端的连接对象,以便在每个组件中重用连接对象,所以我已经这样做了:

 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));
 }
 

它给了我“未定义”.我是否应该以另一种方式导入服务?

  最佳答案

这可能是因为当你导出kuzzleService时,.getInstance()给出的承诺尚未解决.

您应该导出.getInstance函数并在componentDidMount中等待它,如下所示:

 export default KuzzleService; // export the singleton directly
 
 async componentDidMount(){
    const kuzzle = await KuzzleService.getInstance();
    console.log(kuzzle);
}
 

  相同标签的其他问题

react-nativeservicewebsocketkuzzle