异步编程的重要性
JavaScript是单线程语言,但需要处理大量异步操作,如网络请求、文件读写、定时器等。Promise是ES6引入的异步编程解决方案,让异步代码更加清晰和易管理。
Promise基础
创建Promise
const promise = new Promise((resolve, reject) => { const success = true; if (success) { resolve("操作成功"); } else { reject("操作失败"); } });Promise状态
- pending - 进行中
- fulfilled - 已成功
- rejected - 已失败
then方法
promise.then(result => { console.log(result); }).catch(error => { console.error(error); });链式调用
Promise支持链式调用,避免回调地狱:
fetchUser().then(user => fetchPosts(user.id)).then(posts => fetchComments(posts[0].id)).then(comments => console.log(comments)).catch(error => console.error(error));Promise.all并发
处理多个异步操作并行执行:
const promises = [fetchUser(), fetchPosts(), fetchComments()]; Promise.all(promises).then(([user, posts, comments]) => { console.log(user, posts, comments); });async/await
ES8引入的async/await让异步代码更像同步代码:
async function getData() { try { const user = await fetchUser(); const posts = await fetchPosts(user.id); return posts; } catch (error) { console.error(error); } }总结
Promise是JavaScript异步编程的核心概念。掌握Promise和async/await,将让你能够优雅地处理复杂的异步流程。