JS Async/Await

创建于 2024-12-03 / 40
字体: [默认] [大] [更大]

Await 语法

函数前的关键字 await 使函数等待 promise:

let value = await promise;

await 关键字只能在 async 函数中使用。


实例

让我们来学习如何使用它。

async function getFile() {
  let promise = new Promise(function(resolve, reject) {
    let req = new XMLHttpRequest();
    req.open('GET', "mycar.html");
    req.onload = function() {
      if (req.status == 200) {resolve(req.response);}
      else {resolve("File not Found");}
    };
    req.send();
   });
   let result = await promise;
   document.getElementById("demo").innerHTML = result;
}

getFile();

亲自试一试 »


浏览器支持

ECMAScript 2017 引入了 JavaScript 关键字 asyncawait

下表注明了首个完全支持两者的浏览器版本:

Chrome 55 Edge 15 Firefox 52 Safari 11 Opera 42
Dec, 2016 Apr, 2017 Mar, 2017 Sep, 2017 Dec, 2016



0 人点赞过