"Utilize the await/async and promise functions to pause and wait for a code to

I am facing an issue with using await/async in conjunction with Promise.all to retrieve arrays and proceed with the code. However, when I introduce a delay in the code, it seems like it's not functioning as expected. Below is my code snippet:

    async getAllTheUnits() {
        // obtain all units
        console.log('allunits called 1')
        let unitRef = db.collection('units')
        try {
            let allUnitsSnapShot = await unitRef.get()
            await Promise.all(allUnitsSnapShot.docs.map(async (doc) => {
                let u = doc.data()
                u.id = doc.id
                await this.allOfTheUnits.push(u)
            }))
            console.log('allunits called 2 ', this.allOfTheUnits.length)
        }
        catch (err) {
            console.log('Error getting all the units', err);
        }
    },
    async getAllTheWeeks() {
        // retrieve all weeks
        console.log('allweeks called 1')
        let weekRef = db.collection('weeks')
        try {
            let allWeeksSnapShot = await weekRef.get()
            await Promise.all(allWeeksSnapShot.docs.map(async (doc) => {
                let w = doc.data()
                w.id = doc.id
                await this.allOfTheWeeks.push(w)
            }))
            console.log('allweeks called 2 ', this.allOfTheWeeks.length)
        }
        catch (err) {
            console.log('Error getting all the weeks', err);
        }
    },

Below is a simplified function where these other functions are called:

    async initUsersCourse() {

        console.log('1')

        await this.getAllTheUnits()
        await this.getAllTheWeeks()

        console.log('2')

        const allUnits = this.allOfTheUnits
        const allWeeks = this.allOfTheWeeks

        console.log('3')
        console.log('allUnits ', Array.isArray(allUnits), allUnits.length   )
        console.log('allWeeks ', Array.isArray(allWeeks), allWeeks.length)
    }

As mentioned earlier, if I introduce a settimeout in the getAllTheWeeks function to simulate a delay, the initUsersCourse function proceeds without waiting and moves on to console.log('2')

Answer №1

To meet the requirements, your function must be able to return a promise that resolves after a set timeout:

async getAllTheWeeks() {
    return new Promise( resolve => setTimeout( resolve, 2000 ) );
}

In order to address your specific code issue, it's important to note that Promise.all requires an array of promises as input. Therefore, the function used in your allWeeksSnapShot.docs.map should also return a promise. If this is not currently the case, promise.all will need to be adjusted accordingly.

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

Vue/Vuex - using async dispatch for AJAX requests in multiple components

I am working with vuex and using a store module to load user lists in my app through ajax. After the list is loaded, it doesn't fetch again if it's already present in the vuex store. I have implemented this logic in the main application layout as ...

How can I troubleshoot the overflow-y problem in a tab modal from w3 school?

https://www.example.com/code-sample overflow: scroll; overflow-y: scroll; When I type a lot of words, they become hidden so I need to use overflow-y=scroll. Despite trying both overflow: scroll; and overflow-y: scroll;, I have been unable to achieve the ...

jQuery is not updating the div as expected

While typing out this question, I'm hoping to uncover a solution that has eluded me so far. However, just in case... About a year ago, I successfully implemented something similar on another website and went through the code meticulously. Surprisingl ...

How should .has(), .get() and .set() be properly implemented for a JavaScript Map() within an ExpressJS server?

Feeling thrown off by javascript Map()? My query revolves around javascript Map() - the set, get, and has() functions. Despite thinking I was an expert, it seems I still have things to learn... Situation: I'm dealing with a 'global' map sto ...

regex execution and testing exhibiting inconsistent behavior

The regex I am using has some named groups and it seems to match perfectly fine when tested in isolation, but for some reason, it does not work as expected within my running application environment. Below is the regex code that works everywhere except in ...

Exploring tailored markup features in Next.js version 13

I am trying to optimize my website for social media sharing on platforms like WhatsApp. I have been experimenting with different methods to set custom markup in Next.js 13, but haven't achieved the desired outcome yet. Your help and insight are greatl ...

Transforming the output from a processor into an array structure

Being a newcomer in the field of development, I have a question about how to retrieve data based on my requirements and what is considered the best practice? This is the structure of my design: JavaScript (Ajax call) >> ashx handler (Access database and ...

I am looking to dynamically generate HTML elements using AngularJS based on data from a JSON file

Although there are existing answers to this question, I have a specific approach that I need help with. I've already made progress but could use some guidance. This is my Controller : angular.module('dynamicForm.home-ctrl',[]) .con ...

Struggling to align the image elements accurately

I am aiming to create a layout similar to the image displayed below. To be more specific, my goal is to scatter smiley faces randomly within a 500px area while also having a border on the right side of the area. However, with the current code I'm us ...

best method for embedding javascript code within html (within a script tag)

In my quest to create dynamic HTML using jQuery and insert it into a specific div on my website, I encountered an issue. Specifically, I am attempting to generate an anchor element where both the href and label are determined by JavaScript variables. Here ...

Utilizing jQuery for AJAX-Based Deletion of Records

Hey, I stumbled upon a code snippet that allows me to delete a row from my database using Ajax. However, there seems to be an issue where the table that should disappear when deleted is not working properly. Here is the JavaScript code: <script type=" ...

Display a unique button and apply a strike-through effect specifically for that individual list item

I've encountered an issue with my code that is causing problems specifically with nested LI elements under the targeted li element: $('#comment-section .comment-box a#un-do').hide(); $('#comment-section ul li[data-is-archived="true"]& ...

a guide on showcasing a table according to a specific column's data (CSV Path)

I currently have a table structured like this: File Name File path MyFile1.csv D:\tmp\MyFile1.csv MyFile2.csv D:\tmp\MyFile1.csv As of now, my primary table is displayed as shown below: <div class="panel-body table-res ...

Different ways to provide user feedback on a SPA website following AJAX requests

I have a single-page application website developed using React.js. What are some options for notifying the user of successful/failed/pending AJAX calls resulting from various user interactions? I am aware of Toastr-style messages that appear in the corner ...

Troubleshooting the Problem of Adding Class with jQuery Click

Good day, I've been struggling with this issue all day. Almost got it working but not quite there yet. The problem is that I need the corresponding paragraph (#p-1 etc) to remain highlighted once the thumbnail is clicked. I have customized a plugin fo ...

Discover how to shallow test for the presence of a wrapped component using Jest and Enzyme

Currently, I am in the process of testing a component that dynamically renders another wrapped component based on certain conditions. My testing tools include enzyme and jest, with the root component being rendered using the shallow() method. The main chal ...

Using jQuery to insert a new string into the .css file

I'm currently working on a jQuery function to make my font size responsive to changes in width. While I am aware of other options like Media Query, I prefer a solution that offers smoother transitions. Using vw or vh units is not the approach I want t ...

The JavaScript code appears to be missing or failing to execute on the website

Encountering a console error while trying to integrate jQuery into my website. The JavaScript file is throwing an error in the console that says: Uncaught ReferenceError: $ is not defined catergory.js:1 Even after following the suggested steps in this an ...

What could be causing my Vue JS and Laravel download feature to produce corrupt files?

Currently, I'm working on a download feature that allows users to download files of all types that they have uploaded. Although the downloading feature is functioning properly - files are appearing in my downloads folder and the file type is recognize ...

Is there a way to pre-fill meta tags in Nuxt before the page finishes loading?

Having a Nuxt3 application, I encounter an issue where a blog article fetched from Firestore using a path variable ID is not populating the title and meta tags (<Title> and <Meta>) in time for SEO optimization. Despite setting SSR to true and p ...