中國(guó)建設(shè)部官方網(wǎng)站魯班獎(jiǎng)網(wǎng)絡(luò)推廣的方法包括
在JavaScript中,await
用于暫停異步函數(shù)執(zhí)行,等待Promise
對(duì)象的解決。當(dāng)Promise
對(duì)象解決時(shí),await
將返回被解決的值,否則它將拋出一個(gè)被拒絕的Promise
錯(cuò)誤。
下面是一些使用await
的例子:
- 使用
await
等待一個(gè)Promise對(duì)象
async function getData() {const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');const data = await response.json();console.log(data);
}
- 使用
await
等待Promise.all解決所有Promise對(duì)象
async function getAllData() {const [ userData, postdata, commentsData ] = await Promise.all([fetch('https://jsonplaceholder.typicode.com/users'),fetch('https://jsonplaceholder.typicode.com/posts'),fetch('https://jsonplaceholder.typicode.com/comments')]);const users = await userData.json();const posts = await postdata.json();const comments = await commentsData.json();console.log(users, posts, comments);
}
在這個(gè)例子中,Promise.all
將等待所有Promise
對(duì)象都解決后,再返回結(jié)果。使用await
來解決每個(gè)Promise
對(duì)象返回的JSON
數(shù)據(jù),最后打印結(jié)果。
需要注意的是,在使用await
時(shí)需要在一個(gè)異步函數(shù)中使用,否則會(huì)報(bào)錯(cuò)。