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

Incorporate JavaScript code into contentWindow

Attempting to utilize a Javascript postMessage function, similar to how it can be done with an iframe, but now with an embed element. The reason for using an embed is due to the bug in IOS devices which causes issues with setting iframe width and height. ...

unable to locate the font file I recently downloaded in the Windows terminal

Interested in customizing your Windows terminal? I recently decided to change my font style and downloaded the desired one. However, despite seeing the font in control panel and trying the "downloading for every user" option, my terminal still can't l ...

Assign a value to ng-model using JavaScript

Encountering an issue while working with JavaScript in AngularJS. There is a text field identified by id="longitude". <input type="text" data-ng-model="newwarehouse.longtitude" id="longitude"/> The value of this field is being set using JavaScript. ...

Firing a custom jQuery event when a page loaded via AJAX is complete, ensuring it is triggered

I am facing an issue with a particular scenario. There is a page that contains a script to load a child page and log a custom event, which is triggered in a Subform. --Index.html-- <body> <input type="button" class="clickable" value="Load child ...

What is the process for running .js files on my browser from my local machine?

Hi there! I'm trying to figure out how I can create a JavaScript game in TextMate on my Mac. I want to have a regular .js file, then open it and run it in Chrome so that whatever I have coded - for example, "Hello World!" - will display in the browser ...

Show categories that consist solely of images

I created a photo gallery with different categories. My goal is to only show the categories that have photos in them. Within my three categories - "new", "old", and "try" - only new and old actually contain images. The issue I'm facing is that all t ...

Experiencing problems with the Datepicker and cloning functionality in JQuery?

This is the section of code responsible for cloning in JavaScript. $(document).on("click", ".add_income", function () { $('.incomes:last').clone(true).insertAfter('.incomes:last'); $(".incomes:last").find(".income_date_containe ...

How long does it take to delete and recreate a cloudfront distribution using AWS CDK?

I am currently undergoing the process of migrating from the AWS CDK CloudfrontWebDistribution construct to the Distribution Construct. According to the documentation, the CDK will delete and recreate the distribution. I am curious about the total duration ...

Encountering a problem with loading ajax data in jVectorMap

I'm currently facing an issue where I am unable to load data from visitors into a map created using the jvectormap plugin. This problem is really frustrating me as I can't seem to fetch the data through ajax, although it works fine when I input ...

Is there a way to modify the document title using .ready()?

As I work with nested layouts in Ruby on Rails, one particular layout requires me to extract a string from a div and use it as the title of the document. What is the proper method (if there is one) to accomplish this task? <script type="text/javascri ...

Prevent the hover() effect from affecting all div elements at once

I am aiming to achieve a function where hovering over a div with the "rectangle" class will display another div with the "description" class. Initially, the description div will have a display value of "none", but upon hovering, it should become visible. ...

What is the origin of the second parameter in an arrow function that returns another arrow function in a React component with Redux?

I'm having trouble understanding where the (val) parameter is coming from in the returned arrow function. I understand that max/minLength is an arrow function taking an argument set on the input field (3 and 25), and it returns another arrow function ...

make changes to the current selection in the drop-down menu

Imagine I have a select list with 3 options: <select> <option>1</option> <option>2</option> <option>3</option> </select> My goal is to create a textfield and button that will allow me to upd ...

The leaflet_Ajax plugin is constantly searching for the default marker symbol located at js/images/marker-icon.png

Although I'm relatively new to Leaflet, I have experience creating interactive maps in the past. Recently, I've been working on a project involving displaying GPS data from a UAV. The UAV transmits location information to a server, which then ret ...

Troubleshooting: Angular version 4.3 Interceptor malfunctioning

I have been trying to implement new interceptors in Angular 4.3 to set the authorization header for all requests, but it doesn't seem to be working. I placed a breakpoint inside the interceptor's 'intercept' method, but the browser didn ...

Creating a new Express JS application

I've encountered an issue with my express application. When I run the server and navigate to localhost in my browser, the index page loads but without the image that should be displayed. The browser console shows a 404 error for the image URL. GET ht ...

Transfer data from distinct arrays to separate variables

I have 2 arrays structured like this: let dataA = [{"id": "a1", "name": "Alpha"}, {"id": "a2", "name": "Beta"}, {"id": "a3", "name": "Gamma&quo ...

Signing in using Passport.js with mongoDB authentication

Apologies if this question appears redundant, but I am struggling to resolve an issue with a "MISSING CREDENTIALS" error when trying to implement user login using email and password. Despite going through numerous responses, none have provided a solution. ...

How to add multiple entries using Node.js and Tedious

I am currently working with an array of customer objects that I need to insert into a SQL database. These customer objects are retrieved from the request data. For this task, I am utilizing Tedious for handling the request and Tedious Connectionpool to ma ...

The application monitored by nodemon has halted - awaiting modifications in files before restarting the process

1. My ProductController Implementation: const Product = require('../models/product') //Creating a new product => /ap1/v1/product/new exports.newProduct = async(req, res, next) => { const product = await Product.create(req.body); re ...