Ensure that a function completes before moving on in JavaScript

I am attempting to modify the save method so that it waits for this.collection.create() to complete before running, in order to prevent a potential crash.

class UserRepository extends BaseRepository<User>
{
    constructor()
    {
        super();

        this.collection = this.db.collection('users');
        this.collection.create().then(res => {
            if (res.code === 200)
            {
                // collection successfully created
            }
        }).catch(err => {
            if (err.code === 409)
            {
                // collection already exists
            }
        });
    }
}

class BaseRepository<T>
{
  protected db: Database = Container.get('db');
  protected collection: DocumentCollection;

  public save(model: T): void
  {
    this.collection.save(model);
  }
}

Now, I can implement it like this:

const userRepository = new UserRepository();
userRepository.save(new User('username', 'password'));

I have considered two solutions:

  1. Execute this.collection.create() synchronously
  2. Create a property named isCollectionReady and include a small loop in the save method to wait for the value of isCollectionReady to change to true.

Is there a more effective way to achieve this?

Answer №1

Avoid using a loop in JavaScript since it is single-threaded, and the async event may not complete.

Instead of looping, save the Promise for initialization and create a chain as shown below:

class UserRepository extends BaseRepository<User>
{
    constructor()
    {
        super();

        this.collection = this.db.collection('users');
        this._initPromise = this.collection.create().then(res => {
            if (res.code === 200)
            {
                // collection created successfully
            }
        }).catch(err => {
            if (err.code === 409)
            {
                // collection already exists
            }
        });
    }

    ensureInitialized() {
        return this._initPromise;
    }
}

class BaseRepository<T>
{
  protected db: Database = Container.get('db');
  protected collection: DocumentCollection;

  public ensureInitialized() {
      return Promise.resolve();
  }

  public save(model: T): Promise<void>
  {
      return this.ensureInitialized()
          .then(() => this.collection.save(model));
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine using Lodash whether there is an object in an array that matches the ID from a separate array

There is a user array defined as follows: var users = [{ id: 1, name: 'ABC', isDisplay: true }, { id: 2, name: 'XYZ', isDisplay: true }, { id: 3, name: 'JKL', isDisplay: true }]; Additionally, there is another arra ...

Issues with jQuery AJAX, occasionally experiencing repeated requests

Currently, I am in the final stages of revamping our JavaScript system by transitioning from Prototype to jQuery. We have numerous AJAX requests that are triggered when specific events occur on certain elements. One instance of this is when a new event is ...

When attempting to import css-animator in Angular2/Typescript, a 404 error is displayed, indicating that the

Recently, I delved into the world of Angular2 and decided to experiment with some animations using css-animator package.json "dependencies": { "@angular/common": "2.0.0-rc.3", "@angular/compiler": "2.0.0-rc.3", "@angular/core": "2.0.0-rc.3", ...

The enigmatic jQuery AJAX glitch is craving additional arguments

My website uses jQuery's ajax function to handle user signups. Despite using similar code throughout the site, I encountered an error while trying to execute the code below: Error Message: uncaught exception: [Exception... "Not enough arguments" nsr ...

Dismiss Bootstrap by clicking anywhere

I have a specific input that is displayed when clicked and disappears with the next click: <a href="#;" class="asset_info" data-asset_id="{{ asset.pk }}" data-toggle="focus" tabindex="0" data-placement="left" data-trigger="focus" >Hello</a> ...

jQuery slider - display unlimited images

Currently, I am encountering issues with a Flickity carousel of images. When an image/slide is clicked, a modal window opens to display a zoomed-in version of the image. The problem arises when there are more or fewer than 3 images in the slider — my cod ...

Interacting with icons using TouchableOpacity and onPress functionality

I am attempting to implement onPress functionality for icons using TouchableOpacity. However, when I click on the icon, nothing happens and there are no console logs displayed. I have also tried enclosing the icon within an additional View, but that appro ...

Obtain element by selecting a specific class using Javascript

<select class="tmcp-field tillagg-width tm-epo-field tmcp-select" name="tmcp_select_30" data-price="" data-rules="" data-original-rules="" id="tmcp_select_ ...

Fetching the jquery variable within an HTML document: A step-by-step guide

Here is the content of my check.js JavaScript file, which includes a function: function fun2(userid) { $.ajax({ type: 'POST', url: 'ex.php', data: {userid: userid}, success: function (data) { ...

Leverage JSON data in JavaScript

Having some trouble figuring out how to incorporate JSON values into my JS script. Any assistance would be greatly appreciated as I am still new to this! Below is the snippet of code where I need the values (lat and lon) to be inserted: var map; functio ...

By default, make the initial element of the list the selected option in an AngularJS select input

I'm running into an issue with setting the first element in my ng-repeat list within a select input. Here is the code snippet causing the problem: <div> <span >OF</span> <select ng-model="eclatementCourante.ordreFabricationId" n ...

Obtain the Enum's Name in TypeScript as a String

I am currently looking for a solution to transform the name of an enum into a string format. Suppose I have the following Response enum, how can I obtain or convert 'Response' into a string? One of my functions accepts any enum as input and requi ...

using the useEffect hook to create a loop that runs infinitely

For my project, I am working on updating data in firebase. The issue that I'm facing is that the data seems to be constantly looping, causing potential crashes. Is there a way to stop this loop and prevent any crashing? import "./App.css"; ...

"Utilizing Firebase Functions to update information in the Firebase Realtime Database on a daily basis

Currently, I am in the process of working on a project where I aim to provide users with a daily percentage of points based on their current available points and update this data in my Firebase database. My goal is to add points for users on a day-to-day b ...

Authentication with Angular 4 and Firebase 2

I'm having some difficulty learning how to authenticate users using Angular and Firebase. When I run the Angular app using ng serve in the terminal, I keep getting this ERROR message: ERROR in /Users/.../Desktop/angular/fireauth/node_modules/angul ...

GraphQL/Relay Schema "Field cannot be queried..."

I'm encountering an issue when trying to query specific fields in graphql/relay. My goal is to retrieve the "courseName" field for Courses from the schema provided below. For instance, if I query the User with: { user(id:1){firstname,lastname}} T ...

Generating React Components Dynamically using TypeScript

Attempting to generate an element in React using Typescript based on the given tagName passed as props, along with additional relative element properties depending on that particular tagName. Take a look at the code snippet below: type ElementProps<Tag ...

Having trouble updating the DataTable with extra details retrieved from a new URL

I'm currently utilizing the DataTable plugin. After loading the DataTable, my aim is to reload the table, while keeping the existing content intact, and adding information gathered from a separate json file. However, I'm encountering an issue wh ...

I'm having trouble getting my innerHTML command to update anything on the webpage, and the reason is eluding me

Below is the code snippet provided: <div id="js"><button onclick="document.getElementById('js').innerHTML=('<form> <input type=text name=tick1></input> <input type=text name=tick2></input> ...

Issue with my "message.reply" function malfunctioning in Discord.JS

I'm currently learning how to use discord.Js and I am facing an issue with my message.reply function not working as expected. I have set up an event for the bot to listen to messages, and when a message containing "hello" is sent, it should reply with ...