The function error is currently in a waiting state as it already includes an

I encountered a particular issue that states: "await is only valid in async function."

Here is the code snippet where the error occurs:

    async function solve(){
                var requestUrl = "url";

                $.ajax({url: "requestUrl", success: function(result){
                    if(result.length < 3){
                        return false;
                    }else{
                        if(result.substring(0, 3) == "OK|"){
                            var ID = result.substring(3);

                            for(var i=0; i<24; i++){
                                var ansUrl = "url"+ID;  

                                $.ajax({url: "ansUrl", success: function(ansresult){
                                        if(ansresult.length < 3){
                                            return ansresult;
                                        }else{
                                            if(ansresult.substring(0, 3) == "OK|"){
                                                return ansresult;
                                            }else if (ansresult != "ERROR"){
                                                return ansresult;
                                            }
                                        }
                                    }
                                });
                                 await sleep(5000); // <-- ERROR
                            }

                        }else{
                            return ansresult;   
                        }
                    }
                },
                fail: function(){
                    return "";
                    }
                });

            }
 solve();

The initial function didn't have the 'async' keyword so I added it at the beginning but still faced the same error message. It's unclear whether the problem lies within the AJAX calls.

Answer №1

Make sure to avoid using the await keyword within the success callback of your ajax call. Instead, incorporate async function solve without relying on success and fail callbacks when dealing with promises in conjunction with async/await.

Utilize the promise returned by $.ajax, employ await where necessary, and simplify your code structure by reducing nesting:

async function solve() {
    try {
        const requestUrl = "url";
        const result = await $.ajax({url: requestUrl});
//                     ^^^^^
        if (result.length < 3) {
            return false;
        } else if (result.substring(0, 3) == "OK|") {
            const ID = result.substring(3);
            for (let i=0; i<24; i++){
                const ansUrl = "url"+ID;  
                const ansresult = await $.ajax({url: ansUrl});
//                                ^^^^^
                if (ansresult.length < 3) {
                    return ansresult;
                } else if(ansresult.substring(0, 3) == "OK|") {
                    return ansresult;
                } else if (ansresult != "ERROR") {
                    return ansresult;
                }
                await sleep(5000); // works here!
            }
        } else {
            return ansresult; 
        }
    } catch(e) {
        return "";
    }
}
solve().then(console.log);

Answer №2

Modify the primary ajax request to resemble the following:

success: async function(data)

The utilization of await within that nested function is not appropriate without declaring it as async

Answer №3

Remember, when using the await keyword, the containing function must be declared as an async function - Make sure to mark the parent function as async.

If you're working with ajax callbacks, simply switch out success: function( for success: async function(

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

Debugging JavaScript in ASP .NET (solving quick breakpoint problems)

There seems to be a mystery about setting breakpoints in my JavaScript code - sometimes it works, other times it doesn't. Despite all efforts, I can't seem to figure out what factors contribute to this inconsistency. While debugging the dynamic p ...

Tips for managing mouse over events in legends on highcharts

I have successfully implemented mouseover/mouseout event handling for donut slices. Please review my code below: http://jsfiddle.net/nyhmdtb8/6/ Currently, when I hover over a slice, it highlights that slice and greys out all others. Is it possible to ac ...

Create pathways for direct access

I've been studying some code written by someone else to improve my understanding. The way they are setting up routes seems a bit unclear to me. app.use('/dist', express.static(path.join(CURRENT_WORKING_DIR, 'dist'))) // mount rou ...

Cleaning up objects from memory in JavaScript following an AJAX request

I am developing a web application with dynamic content loading. In my code, I have a main container div (<div id="container"/>) where I use AJAX to load HTML content. // function overwritten by loadMenu functions // called before loading a new sect ...

Passing the title of a page as data to a component in Next.js

I am currently working on setting a custom title for each page within my next.js project. Here is an example of a simple Layout: const MainLayout = props => { return ( <Layout style={{ minHeight: "100vh" }}> <Head> < ...

The Veux Store is throwing an error message that says "Array is

When retrieving data from the Vuex Store, I start by checking if the array is present. Following that, my next step is to verify whether the noProducts object at index 0 exists. This validation process is important because the tweakwiseSortedProducts vari ...

What is the best way to address Peer dependency alerts within npm?

Here is a sample package.json that I am using for my application: dependencies : { P1 : “^1.0.0” // with peer dependency of p3 v1 P2 : “^1.0.0” // with peer dependency of p3 v2 } P1 and P2 both have peer dependencies on ...

Checking if the current time falls within a specific time range, without taking the year into account, using Javascript

I am looking to add a special feature using JavaScript. I would like to change the background images of my webpage to ones related to Christmas during the holiday week, and have it repeat every year. How can I determine if the current date and time fall ...

Is it possible to simultaneously verify if an array is empty within an Object along with checking the other fields?

Let's say I have an object that has the following structure: filter: { masterName: '', service:[], } What is the best way to determine if both the array and masterName field are empty? ...

Tips for properly panning across the canvas

I added event listeners to capture mouse movement, clicks, and releases in my code. canvas.addEventListener('mousemove', onMouseMove, false); canvas.addEventListener('mousedown', onMouseDown,false); canvas.addEventListener('mouseu ...

The selected option is not visually highlighted in the ui-select due to a programming issue

angular version: AngularJS v1.3.6 http://github.com/angular-ui/ui-select : Version: 0.8.3 var p1 = { name: 'Ramesh', email: '[email protected]', age: 99 }; $scope.people = [ { name: 'Amalie', ...

Encountering an issue where an error message indicates that a variable previously declared is now undefined

Currently, I am working on developing a small test application to enhance my coding skills. However, I have encountered a roadblock while attempting to display dummy information from a mongodb database that I have set up. I have tried various solutions bu ...

"Embracing Dynamism: Enhancing Vue3 with Dynamic Routing for

Seeking guidance on implementing a dynamic component with Dynamic Routing in Vue3. The goal is to render a component based on the parameter (path named id) from router.ts. In the router.ts file, there is a dynamic parameter called id that needs to be used ...

Choosing CSS/JS selector: Pick the final element with a class that does not match

My goal is to extract the most recent td element from the latest tr within an HTML table, ensuring that the latest td does not belong to the disabled class. I am attempting to achieve this using pure JavaScript with CSS selectors (without relying on jQuer ...

Utilizing clip-path polygons for effective styling on Firefox and iOS

I have been working on a plugin to create animated modal boxes by utilizing the clip-path property. However, I have encountered an issue where this code only seems to work in Chrome. You can view the codepen demo here. Unfortunately, it appears that Firef ...

Is there a way to dynamically alter the background style of a div by clicking on it multiple times using Javascript?

I am attempting to create a calendar where each day changes its background color between blue and green when clicked, using JavaScript and CSS. It should function similar to a toggle feature. The default color is blue, and I have successfully made the days ...

jquery allows you to toggle the visibility of content

There are two divs with a button positioned above them. Initially, only one div, the catalogusOrderBox, is visible. When the button named manualButton is clicked, it should display the manualOrderBox div while hiding the catalogusOrderBox div. The text on ...

Problem with Captcha when Google Data Compression Proxy is activated

Recently, users have been reporting issues with the CAPTCHA code not functioning properly while using Android Chrome with Data Compression enabled. Upon closer examination, we discovered that although we save the CAPTCHA into the SESSION, it is not access ...

JavaScript client side event that references the sender object ID in an aspx file

Can someone provide assistance with an issue in the code block below? function(s, e) { form1.hfRaiseEvent.value = s.ID; } This particular function is triggered when the Client Side Click Event occurs. From my understanding, s refers to the Sender Obj ...

The function was triggered upon the form loading, instead of being activated when the button was clicked

The issue I am facing is that in the code snippet below, the function readCSV() is not being triggered when buttons for filepath1 and filepath2 are clicked. The function is only executed on form load. I was expecting it to work on button click as well. I ...