Can i use async funtion inside
XMLHttpRequest.addEventListener('readystatechange',async function(){
or
setTimeout(async function(){
or
element.addEventListener('click',async function(){
Is syntax like that correct/valid?
I need await function but when i use it inside non async functions like below i got error: "Uncaught SyntaxError: await is only valid in async functions"
All of the APIs in question expect functions which do not expect any return values. So the primary thing you gain is ability to use await
inside the function. Which, per your comment, it seems like that's what you want. It only takes 3 minutes to test it yourself and see -
setTimeout(async _ => { const res = await fetch(`https://httpbin.org/json`) const data = await res.json() console.log(data) }, 1000) console.log("loading...")
loading...
{
"slideshow": {
"author": "Yours Truly",
"date": "date of publication",
"slides": [
{
"title": "Wake up to WonderWidgets!",
"type": "all"
},
{
"items": [
"Why <em>WonderWidgets</em> are great",
"Who <em>buys</em> WonderWidgets"
],
"title": "Overview",
"type": "all"
}
],
"title": "Sample Slide Show"
}
}
But you're missing the benefit of async
and await
by breaking out of the promise chain by using setTimeout
in this way. It would be much better to write a promise around setTimeout
instead. Rather than punting to the event queue, this keeps data moving through the promises and allows you to sequence any asynchronous portions of your program -
const sleep = ms => new Promise(r => setTimeout(r, ms)) const fetchJson = (url, opts = {}) => fetch(url, opts).then(r => r.json()) async function main() { console.log("loading...") await sleep(1000) const data = await fetchJson(`https://httpbin.org/json`) console.log(data) return "done" } main().then(console.log, console.error)
loading...
{
"slideshow": {
"author": "Yours Truly",
"date": "date of publication",
"slides": [
{
"title": "Wake up to WonderWidgets!",
"type": "all"
},
{
"items": [
"Why <em>WonderWidgets</em> are great",
"Who <em>buys</em> WonderWidgets"
],
"title": "Overview",
"type": "all"
}
],
"title": "Sample Slide Show"
}
}
done
The same applies for your addEventListner
examples
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.