Application becomes unresponsive following database write caused by an infinite loop

I have a user_dict object that is generated by fetching data from a Firebase database. Once the user_dict object is created, I store a copy of it within a profile child under the uid.

Although the necessary information is successfully saved to the database, my is_profile_ready boolean never becomes true, causing my while loop to get stuck. Is there a more effective way to handle this situation? I have struggled with promises and async/await implementation.

Could the issue lie with my while loop, or am I making another mistake that prevents is_profile_ready from turning true?

async function handleTestStart() {
    traceFunction()
    character.style.backgroundImage = "url(character.png)"
    left_button.style.visibility = 'visible'
    right_button.style.visibility = 'visible'
    showLogoAnimation()
    setTimeout(function () {
        let start_time = new Date().getTime()
        while (!is_user_dict) {
            let end_time = new Date().getTime()
            let time = end_time - start_time
            if (time > 10000) {
                timeoutError()
            }
        }
        let is_profile_ready = createProfile()
        let start_time2 = new Date().getTime()
        while (!is_profile_ready) {
            let end_time2 = new Date().getTime()
            let time2 = end_time2 - start_time2
            if (time2 > 10000) {
                timeoutError()
            }
        }
        hideLogoAnimation()
        condition_category_array.forEach(function (condition_category) {
            user_dict['more_info'].push(condition_category)
        })
        category = user_dict['more_info'][0]
        backup_user_dict = deepCopyObject(user_dict)
        nextQuestion()
    }, 2000)
}

function createProfile() {
    let current_user_id = firebase.auth().currentUser.uid
    console.log('createProfile currentUser is ', current_user_id)
    firebase.database().ref().child('profile').child(current_user_id).set({
        'user_dict' : user_dict
    }).then(() => { return true })
}

Edit: Frank suggested a solution which I'm getting an error (cannot read property "then" of undefined) on is_profile_ready.then. Copying the code below for easier reading.

async function handleTestStart() {
    traceFunction()
    character.style.backgroundImage = "url(character.png)"
    left_button.style.visibility = 'visible'
    right_button.style.visibility = 'visible'
    showLogoAnimation()
    let start_time = new Date().getTime()
    while (!is_user_dict) {
        let end_time = new Date().getTime()
        let time = end_time - start_time
        if (time > 10000) {
            timeoutError()
        }
    }
    let is_profile_ready = createProfile()
    let start_time2 = new Date().getTime()
    is_profile_ready.then((result) => {
        let end_time2 = new Date().getTime()
        let time2 = end_time2 - start_time2
        if (time2 > 10000) {
            timeoutError()
        }
        hideLogoAnimation()
        condition_category_array.forEach(function (condition_category) {
            user_dict['more_info'].push(condition_category)
        })
        category = user_dict['more_info'][0]
        backup_user_dict = deepCopyObject(user_dict)
        nextQuestion()
    })
}

function createProfile() {
    let current_user_id = firebase.auth().currentUser.uid
    console.log('createProfile currentUser is ', current_user_id)
    firebase.database().ref().child('profile').child(current_user_id).set({
        'user_dict': user_dict
    }).then(() => { return true })
}

Answer №1

It appears that you may be under the impression that the createProfile function directly returns a boolean value of true. However, upon closer examination, you will realize that it actually returns a more intricate entity referred to as a Promise, which signifies a promise for a future value.

To effectively handle this asynchronous behavior and acquire the eventual value, you can employ either the await keyword or attach a callback using the then method of the promise as shown below:

let profileCreationPromise = createProfile()
let startTime = new Date().getTime()
profileCreationPromise.then((result) => {
    let endTime = new Date().getTime()
    let duration = endTime - startTime
    if (duration > 10000) {
        handleTimeoutError()
    }
    hideLogoAnimation()
    conditionCategoryArray.forEach(function (category) {
        userDict['info'].push(category)
    })
    selectedCategory = userDict['info'][0]
    backupUserDict = deepCopy(userDict)
    proceedToNextQuestion()
})

Note: To ensure the above functionality, it is crucial to return the promise at the topmost level of your createProfile function, like so:

function createProfile() {
    let userID = firebase.auth().currentUser.uid
    console.log('Current user ID for createProfile is ', userID)
    return firebase.database().ref().child('profile').child(userID).set({
        'userData': userDict
    }).then(() => { return true })
}

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

Unable to submit form data in AWS Amplify & React: The message "Not Authorized to access createRecipe on type Mutation" is displaying

I've recently set up a project using React and AWS Amplify. I've successfully added some data to DynamoDB in AWS, but when I try to submit form data from my React App, I encounter an error from the API. I'm a bit stuck on what to do next. I ...

methods for obtaining access in JavaScript when dealing with an ArrayList<Object> that has been converted to a JSONArray

I am dealing with an Object ArrayList that contains various variables, stored in an ArrayList of Objects. I then convert it to a JSONArray and pass it to a JSP page. How can I display these objects in a textarea on the JSP page using JavaScript? public cl ...

Trouble experienced with the window.open() function on Safari

When using Safari, it can sometimes block the opening of a new tab through the window.open() function during an ajax call. To bypass this blocking, we must first call window.open() to open a new tab before making the ajax call. Refer to this Stack Overflow ...

What is the syntax for creating a link tag with interpolation in Angular 2 / Ionic 2?

As I work on developing an app using Ionic 2/Angular 2, I have encountered a challenge that I am struggling to overcome. Let me provide some context: I am retrieving multiple strings from a webservice, and some of these strings contain links. Here is an e ...

Extremely sluggish change identification in combination Angular application

We are encountering consistent issues with slow change detection in our hybrid AngularJS / Angular 8 app, especially when dealing with components from different versions of the framework. The problem seems to arise when using older AngularJS components wit ...

Angular2 - Actively selecting a checkbox in an ngFor loop with a reactive form

There is an object retrieved from a database that consists of a list of names with their corresponding IDs, as well as a flag to indicate whether they are selected or not. Object: let items = [{ ID: 1, Name: 'Item A', Selected: 'Y ...

Update the browser value using AJAX without the need to refresh the page

After retrieving a value from an XML file using ajax jquery, I encountered an issue. When I change the value in my XML file, it does not automatically update in the browser. <?xml version="1.0"?> <count><number>5</number></count ...

Pulling JSON Data with Ajax Request

I am attempting to retrieve the following JSON Data: {"status":"success","id":8,"title":"Test","content":"This is test 12"} Using this Ajax Request: $.ajax({ url: 'http://www.XXX.de/?apikey=XXX&search=test', type: "GET", dataType: 'js ...

Locate the word or phrase without a comma

I am currently working on a code that involves finding keys with string values separated by commas. var db = { "name": "Nkosana", "middle": "Baryy", "surname": "walked", "batch_number": "test,b", "temp": ",,67,6,87,86,5,67865,876,67" ...

Achieving uniform width in material ui: Tips for maintaining consistency

I am encountering an issue with the width of my Goal components and can't figure out what is causing it. https://i.stack.imgur.com/jPlyf.png Despite setting the width of the Paper selector to 100%, each Goal component's width remains inconsiste ...

Creating a Distinct Interior Array Separate from the Exterior

I'm currently working on a project that involves creating a 2D array. I want the interior elements of this array to be black while the exterior elements should be white. However, my 2D array doesn't seem to be forming correctly - it looks more li ...

Issue - Basic Data Protection and Unscrambling - Node.js

I have been working on some basic code to encrypt and decrypt text, but I keep encountering an error when using the .final() function of createDecipherIV. I have tried experimenting with different encodings like Binary, Hex, and base64. Node Version: &apo ...

What strategies can I use to keep an element in place while implementing parallax scrolling?

Looking for some assistance with my Codepen project. I am attempting to replicate a layout similar to this BBC article design from the past, but hitting a roadblock with getting my image to be position fixed based on scrolling. I believe that if I can suc ...

Ways to usually connect forms in angular

I created a template form based on various guides, but they are not working as expected. I have defined two models: export class User { constructor(public userId?: UserId, public firstName?: String, public lastName?: String, ...

Error encountered in vue.js due to a ReferenceError when the resize event is used

I'm having trouble obtaining the window height when resizing, and I keep encountering the error ReferenceError: calcOfSliderHeight is not defined. Can someone explain what's happening? Here is my code: let example = new Vue({ el: '#exam ...

Develop a TypeScript class by incorporating a static function from an external library, while ensuring type safety

I am looking to enhance the capabilities of the rxjs5 Observable class by adding a static function. While this can be easily accomplished in plain JavaScript: var myStaticFn = function() { /* ... */ }; Observable.myStaticFn = myStaticFn; this approach w ...

Are there any available resources for comparing the performance of JavaScript libraries?

In preparing a presentation for my company, I am outlining the reasons for choosing jQuery as our primary JavaScript / AJAX library. While most of the work is already completed, it would be beneficial to include a comparison with other libraries, particul ...

Eliminate redundant tags using jQuery

I have a code snippet that I need help with. I want to check for duplicates and if found, display an alert stating that it already exists so users can't insert the same word/tag again. Can someone please assist me? <div id="tags"> <span>a ...

Is there a way for me to showcase the latitude and longitude retrieved from JSON data on a Google Map using modals for each search result in Vue.js?

After receiving JSON data with search results, each containing latitude and longitude coordinates, I am attempting to display markers on a Google map modal when clicking "View Map". However, the code I'm using is not producing the desired outcome. Th ...

If the span id includes PHP data that contains a certain phrase

Hey there, it's my first time posting and I'm in a bit of a bind with this script... Let me give you some background information first I am trying to create a click function for a register button that will check the span id (e.g. $("#username_r ...