欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

ES6 Promise 与 async/await 异步编程

时间:2026年08月12日 05:39:03 浏览:1

ES6 Promise 与 async/await 异步编程


Promise 和 async/await 是 JavaScript 异步编程的核心。


1. Promise 基础


function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('数据');
}, 1000);
});
}

fetchData()
.then(data => console.log(data))
.catch(err => console.error(err));

2. 链式调用与并发


Promise.all([fetch(url1), fetch(url2)])
.then(responses => Promise.all(responses.map(r => r.json())))
.then(data => console.log(data));

3. async/await


async function getData() {
try {
const response = await fetch('https://api.example.com');
const data = await response.json();
console.log(data);
} catch (err) {
console.error(err);
}
}

4. 错误处理



  • 使用 .catchtry...catch

  • 未处理的 Promise 拒绝会导致 unhandledrejection 事件。


async/await 让异步代码看起来像同步,提高可读性。