Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

305
Views
NodeJS async class with singleton design pattern

Problem: Implement the singleton design pattern with async calls in the class. I can't get the values when i import the module into a second file.

Case: Eventually i want to implement this logic for a bearer token update when it expires. I have multiple functions that relies on the token. So when i get a 403 i will update the token and all the other function have acces to this updated token as well.

Script 1:

//File1.js
import axios from "axios";

async function getJson(n) {
  const req = await axios.get(
    `https://jsonplaceholder.typicode.com/todos/${n}`
  );
  return req.data.title;
}

class Todo {
  constructor() {
    if (Todo.instance == null) {
      this.title;
      Todo.instance = this;
    }
    return Todo.instance;
  }

  async init() {
    this.title = await getJson(1);
  }

  async updateTodo(n) {
    this.title = await getJson(n);
  }

  getTodo() {
    return this.title;
  }
}

const todo = await new Todo().init();

export default todo;

Script 2:

const todo = await import('./File1.js');

console.log(todo); //[Module: null prototype] { default: [AsyncFunction (anonymous)] }
todo.updateTodo(3) //TypeError: todo.updateTodo is not a function

Script 2.1:

import todo from './File1.js';
await todo.init();

console.log(todo.getTodo())
await todo.updateTodo(2)
console.log(todo.getTodo())
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Dynamic imports are different from regular imports. When you do:

import module from "./module.js";

module will be equal to the default export, something like:

// module.js
export default function module() {
  // do something
}

In dynamic imports (import()), however, you have to manually access the default export:

const importModule = await import("./module.js");
const module = importModule.default;
module(); // default export module

So in your code you would be doing:

todo.default.updateTodo(3);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!