繁体   English   中英

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

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

我可以在里面使用异步功能吗

XMLHttpRequest.addEventListener('readystatechange',async function(){

或者

setTimeout(async function(){ 

或者

element.addEventListener('click',async function(){

这样的语法正确/有效吗?

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

所有有问题的 API 都期望不期望任何返回值的函数。 因此,您获得的主要好处是能够在 function 中使用await 根据您的评论,这似乎就是您想要的。 自己测试只需要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"
  }
}

但是通过以这种方式使用setTimeout打破 promise 链,您错过了asyncawait的好处。 最好在setTimeout周围写一个 promise 代替。 这不是直接进入事件队列,而是让数据在 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

这同样适用于您的addEventListner示例

暂无
暂无

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

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