admin管理员组文章数量:1401281
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);
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)
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?
Thanks.....
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);
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)
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?
Thanks.....
Share Improve this question asked Mar 1, 2018 at 1:53 cpeddiecpeddie 79917 silver badges41 bronze badges 2-
so ..
json
is a promise, because that's what async functions return – Jaromanda X Commented Mar 1, 2018 at 1:56 - Setup a codepen.io demo – Geuis Commented Mar 1, 2018 at 2:16
3 Answers
Reset to default 4async
functions return promises. Even when you return something from the async function, it's only going to be the value the promise resolves to.
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 );
})
});
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./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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So here:
$(document).ready(function () {
let json = doAjaxGet( "/static/imeiXref.json");
console.log('json: ', json);
processJSONData( json );
});
You're not telling let json
to wait for the response from doAjaxGet
. Its awaiting inside the doAjaxGet
function but everything else is executing sequentially without waiting.
What you want to do is this (I think):
$(document).ready(async function () {
let json = await doAjaxGet( "/static/imeiXref.json");
console.log('json: ', json);
processJSONData( json );
});
Async/await is basically syntactic sugar around promises. await
waits for a promise to resolve, so you have to do async/await at every level you're using the promise chain, or you can just use standard promise.then()
style coding.
I see that this was posted long time ago but i was recently suffering from the same issue. I hope this helps for those who still needs help just like i needed.
// make sure that the function you are waiting for has no async/await keys but wrapped with promise
function doAjaxGet(ajaxurl) {
return Promise((resolve,reject)=>{
$.ajax({
url: ajaxurl,
type: 'GET',
success: function(result){
resolve(result);
},
error:function(){
reject('');
}
});
}
}
// then in the function you wait the results, use async/await
$(document).ready(async function() {
await doAjaxGet("https://jsonplaceholder.typicode./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)
}
本文标签: javascriptjs asyncawait not workingStack Overflow
版权声明:本文标题:javascript - js asyncawait not working - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744282963a2598743.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论