简体   繁体   English

Javascript await 仅在异步函数中有效

[英]Javascript await is only valid in async functions

I have this function to delete items once a popup returns true:一旦弹出窗口返回 true,我就有这个 function 删除项目:

function deleteItems(selectedItems){
    if (selectedItems.length > 0) {
        $("#confirm-popup-modal").modal("show");
        $("#confirm-popup-modal").one('hidden.bs.modal', function (event) {
            if ($("#confirm-modal").val() == "true") {
                var form_data = selectedItems;
                $.ajax({
                    url: "@Url.Action("Delete", @ViewContext.RouteData.Values["controller"].ToString())",
                    method: "POST",
                    data: JSON.stringify(form_data),
                    contentType: "application/json",
                    success: function (result) {
                        if (result.Result == true) {
                            var deleteId = result.Output;
                            await CompletedJobsAccess(deleteId);
                            table.draw();
                        }
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            }
        });
    }
}

Inside the Ajax success is another function called CompletedJobsAccess that will keep looping every 3 seconds to check if a job deletion has been completed:在 Ajax 成功内部是另一个名为 CompletedJobsAccess 的 function ,它将每 3 秒循环一次以检查作业删除是否已完成:

function CompletedJobsAccess(DeleteId){
    return new Promise((resolve,reject)=>{
        var loopInterval = setInterval(function() { 
            $.ajax({
                url: "@Url.Action("Verify", "CompletedJobsAccess", new {area="Base" })",
                method: "POST",
                data: JSON.stringify(DeleteId),
                contentType: "application/json",
                success: function(verifyResult) {
                    if (verifyResult.IS_COMPLETED == true && verifyResult.IS_PROCESSING == false) {
                        if (verifyResult.IS_SUCCESSFUL == true) {
                            console.log(verifyResult.OUTPUT);
                            $.each($.parseJSON(verifyResult.OUTPUT), function(index, value) {
                                if (value.Result == true) {
                                    toastr.success(value.Message);
                                }else{
                                    toastr.error(value.Message);
                                }
                            });
                            clearInterval(loopInterval);
                        } else {
                            toastr.error(verifyResult.ERROR_MESSAGE);
                        }
                    }
                },
                error: function(innerError) {
                    console.log(innerError);
                }
            });
        }, 3000);
    });
}

However, when I load the page, and call deleteItems(selected);, this is the error I get:但是,当我加载页面并调用 deleteItems(selected); 时,这是我得到的错误:

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules未捕获的 SyntaxError:await 仅在异步函数和模块的顶层主体中有效

I tried searching around but I can't find if it can work within an ajax success function.我尝试四处搜索,但找不到它是否可以在 ajax 成功 function 中工作。

EDIT:编辑:

Added async to the ajax success function but the table draw function doesn't run.将异步添加到 ajax 成功 function 但表格绘制 function 不运行。

function deleteItems(selectedItems){
    if (selectedItems.length > 0) {
        $("#confirm-popup-modal").modal("show");
        $("#confirm-popup-modal").one('hidden.bs.modal', function (event) {
            if ($("#confirm-modal").val() == "true") {
                var form_data = selectedItems;
                $.ajax({
                    url: "@Url.Action("Delete", @ViewContext.RouteData.Values["controller"].ToString())",
                    method: "POST",
                    data: JSON.stringify(form_data),
                    contentType: "application/json",
                    success: async function (result) {
                        if (result.Result == true) {
                            var deleteId = result.Output;
                            console.log("table before");
                            await CompletedJobsAccess(deleteId);
                            console.log("table draw");
                            table.draw();
                        }
                        table.draw();
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            }
        });
    }
}

EDIT 2: Updated CompletedJobsAccess to resolve promises:编辑 2:更新 CompletedJobsAccess 以解决承诺:

function CompletedJobsAccess(DeleteId){
    return new Promise((resolve,reject)=>{
        var loopInterval = setInterval(function() { 
            $.ajax({
                url: "@Url.Action("Verify", "CompletedJobsAccess", new {area="Base" })",
                method: "POST",
                data: JSON.stringify(DeleteId),
                contentType: "application/json",
                success: function(verifyResult) {
                    if (verifyResult.IS_COMPLETED == true && verifyResult.IS_PROCESSING == false) {
                        if (verifyResult.IS_SUCCESSFUL == true) {
                            console.log(verifyResult.OUTPUT);
                            $.each($.parseJSON(verifyResult.OUTPUT), function(index, value) {
                                if (value.Result == true) {
                                    toastr.success(value.Message);
                                }else{
                                    toastr.error(value.Message);
                                }
                            });
                            clearInterval(loopInterval);
                            return Promise.resolve();
                        } else {
                            toastr.error(verifyResult.ERROR_MESSAGE);
                            return Promise.resolve();
                        }
                    }
                },
                error: function(innerError) {
                    console.log(innerError);
                }
            });
        }, 3000);
    });
}

Just make the success function async只要成功 function async

 $.ajax({ url: "https://jsonplaceholder.typicode.com/users/3", method: "GET", success: async function(data) { console.log("first - now wait a second..."); await new Promise((res) => setTimeout(res, 1000)); console.log("second, data:",data); }, error: function(innerError) { console.log(innerError); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Working JSFiddle (can't work on this site because of CORS)工作JSFiddle (由于 CORS 无法在此站点上工作)

In CompletedJobsAccess(DeleteId) you return a promise.CompletedJobsAccess(DeleteId) ,您返回 promise。 But the way you set it up it will never execute the resolve function.但是你设置它的方式永远不会执行resolve function。 So your await will wait forever...所以你的await将永远等待......

You could place the line你可以把线

resolve();

right after紧接着

clearInterval(loopInterval);

in your CompletedJobsAccess function to make it work.在您的CompletedJobsAccess function 中使其工作。

Do not return yet another Promise.resolve() like you did in your edited code.不要像在编辑的代码中那样返回另一个Promise.resolve()

A resolve function for a promise is never returned but executed. promise 的解析 function 永远不会返回但会执行。

Try Adding async before all the function keyword like async function deleteItems(selectedItems){ and also $("#confirm-popup-modal").one('hidden.bs.modal', async function (event) { and it should do the job. Try Adding async before all the function keyword like async function deleteItems(selectedItems){ and also $("#confirm-popup-modal").one('hidden.bs.modal', async function (event) { and it should do工作。

You're using await in functions that don't use the async keyword.您在不使用async关键字的函数中使用await await isn't available in regular functions. await在常规函数中不可用。 To solve this, you can change all the functions using await to async function to make it into an asynchronous function.为了解决这个问题,您可以使用await将所有功能更改为async function以使其成为异步 function。

And if you don't want want to go through every function to make it asynchronous, you can just put the entire code inside an asynchronous IIFE如果你不想 go 通过每个 function 使其异步,你可以把整个代码放在异步 IIFE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript 函数 await 仅在异步函数中有效 - Javascript function await is only valid in async functions Await 仅在异步函数中有效 - Await is only valid in async functions javascript await function in script 返回 Uncaught SyntaxError: await is only valid in async functions and the top level body of modules - javascript await function in script returns Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules Javascript:SyntaxError:await仅在异步函数中有效 - Javascript: SyntaxError: await is only valid in async function Await 仅在异步函数中有效:JavaScript NodeJS - Await is only valid in async function: JavaScript NodeJS await 仅在异步函数和模块的顶层主体中有效 javascript 表示错误 - await is only valid in async functions and the top level bodies of modules javascript express error SyntaxError: await 仅在异步函数和模块的顶层主体中有效 - SyntaxError: await is only valid in async functions and the top level bodies of modules Google Cloud / Firebase功能:等待仅在异步功能中有效 - Google Cloud / Firebase Functions: await is only valid in async function await 仅在异步函数和模块的顶级主体中有效 - await is only valid in async functions and the top level bodies of modules await 仅在异步函数和循环中模块的顶层主体中有效 - await is only valid in async functions and the top level bodies of modules in loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM