let value = await promise;
await 关键字只能在 async 函数中使用。
实例
让我们慢慢来学习如何使用它。
基础语法
async function myDisplay() {
let myPromise = new Promise(function(myResolve, myReject) {
myResolve("I love You !!");
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
亲自试一试
等待超时
async function myDisplay() {
let myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() { myResolve("I love You !!"); }, 3000);
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
亲自试一试
等待文件
async function getFile() {
let myPromise = new Promise(function(myResolve, myReject) {
let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() {
if (req.status == 200) {myResolve(req.response);}
else {myResolve("File not Found");}
};
req.send();
});
document.getElementById("demo").innerHTML = await myPromise;
}