問題一覧に戻る
中級async
問題95: await式
await式の使い方を学びましょう。awaitはPromiseの解決を待ち、その結果を取得します。非同期処理を同期的なコードのように書けるため、コールバック地獄やPromiseチェーンの複雑さを避けられます。awaitはasync関数内でのみ使用でき、複数の非同期処理を順番に実行したり、結果を変数に代入したり、分割代入と組み合わせたりできます。モダンJavaScriptの非同期処理のスタンダードです。
async function getUserData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
name: "佐藤",
email: "sato@example.com"
});
}, 200);
});
}
async function main() {
console.log("データ取得中...");
const user = getUserData();
console.log(`名前: ${user.name}`);
console.log(`メール: ${user.email}`);
const { name, email } = getUserData();
console.log(`取得完了: ${name} - ${email}`);
}
main();