簡體   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