简体   繁体   English

我可以在 javascript 的任何地方使用异步函数吗?

[英]Can i use async functions everywhere in javascript?

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"我需要等待 function 但是当我在如下非异步函数中使用它时出现错误:“未捕获的语法错误:等待仅在异步函数中有效”

All of the APIs in question expect functions which do not expect any return values.所有有问题的 API 都期望不期望任何返回值的函数。 So the primary thing you gain is ability to use await inside the function.因此,您获得的主要好处是能够在 function 中使用await Which, per your comment, it seems like that's what you want.根据您的评论,这似乎就是您想要的。 It only takes 3 minutes to test it yourself and see -自己测试只需要3分钟,看看——

 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.但是通过以这种方式使用setTimeout打破 promise 链,您错过了asyncawait的好处。 It would be much better to write a promise around setTimeout instead.最好在setTimeout周围写一个 promise 代替。 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 -这不是直接进入事件队列,而是让数据在 Promise 中移动,并允许您对程序的任何异步部分进行排序 -

 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这同样适用于您的addEventListner示例

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM