js异步/等待不起作用 [英] js async/await not working

查看:375
本文介绍了js异步/等待不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将头缠绕在异步/等待以及如何使用它们上.我正在跟我看过的一些例子(我想)一起写,但是等待实际上并不是在等待ajax响应.这是代码:

I'm trying to wrap my head around async/await and how to use them. I'm following some examples I've seen to the letter (I think), but it the await is not actually waiting for ajax response. Here is the code:

async function doAjaxGet(ajaxurl) {
    const result = await $.ajax({
        url: ajaxurl,
        type: 'GET',
        datatype: "text",      
    });
    return result;
}

$(document).ready(function () {
    let json = doAjaxGet( "/static/imeiXref.json");
    console.log('json: ', json);
    processJSONData( json );
});


function processJSONData(data) {
    console.log('Data: ', data);
    Data = JSON.parse( data);

但是await关键字实际上并不是在等待返回结果.在控制台日志中,我得到以下信息:

But the await keyword is not actually waiting for the result to be returned. In the console log I get the following:

json:  Promise {<pending>}
Data:  Promise {<pending>}                                  controller.js:98 
jQuery.Deferred exception: Unexpected token o in JSON at position 1 SyntaxError: Unexpected token o in JSON at position 1             jquery.min.js:2 
    at JSON.parse (<anonymous>)
    at processJSONData (http://localhost:3000/js/controller.js:99:25)
    at HTMLDocument.<anonymous> (http://localhost:3000/js/controller.js:80:5)
    at l (http://localhost:3000/js/jquery.min.js:2:29375)
    at c (http://localhost:3000/js/jquery.min.js:2:29677) undefined
jquery.min.js:2 Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at processJSONData (controller.js:99)
    at HTMLDocument.<anonymous> (controller.js:80)
    at l (jquery.min.js:2)
    at c (jquery.min.js:2)

但是,如果我实际查看控制台中返回的结果,则数据实际上在那里.因此,似乎await函数不是"awaiting",并且我的代码在ajax调用之后立即继续执行,并且它正在尝试解析尚未返回的JSON数据.我该如何等待?

But if I actually look at the result that is returned in the console, the data is actually there. So it seems that await function is not 'awaiting' and my code continues to execute right after the ajax call, and it is trying to parse JSON data that has not been returned yet. How do I get the await to await?

谢谢.....

推荐答案

async函数返回promise.即使从async函数返回某些内容,它也只会是promise解析为的值.

async functions return promises. Even when you return something from the async function, it's only going to be the value the promise resolves to.

您需要执行以下操作才能使用Promise:

You need to do something like this to use the promise:

$(document).ready(function () {
    doAjaxGet( "/static/imeiXref.json")
    .then(json => {
       console.log('json: ', json);
       processJSONData( json );
    })
});

编辑.这是一个工作片段.请注意,但是,这是下载json而不是字符串,因此无需解析它.这确实是一个与异步问题不同的问题,异步问题似乎还可以.

EDIT. Here's a working snippet. Note, however that this is downloading json not a string, so there is no need to parse it. That's really a different question than the async issue, which seems to be working okay.

async function doAjaxGet(ajaxurl) {
  const result = await $.ajax({
    url: ajaxurl,
    type: 'GET',
  });
  return result;
}

$(document).ready(function() {
  doAjaxGet("https://jsonplaceholder.typicode.com/posts/1")
    .then(json => {
      console.log('json: ', json);
      processJSONData(json);

    })
});


function processJSONData(data) {
  // NOTE: data is already parsed
  console.log('Data: ', data);
  console.log("id: ", data.userId)
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这篇关于js异步/等待不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆