5.Promise,async,await概念(1)
Promise 是 JavaScript 原生提供的异步处理机制,而 async 和 await 是基于 Promise 的语法糖,由 JavaScript 语言和其运行时环境(如浏览器、Node.js)支持,用于更清晰地编写异步代码,从而避免回调地狱。
Promise is a native asynchronous feature in JavaScript, while async and await are syntactic sugar built on top of Promises, supported by the JavaScript language and its runtime environments (like browsers or Node.js), helping write cleaner asynchronous code and avoid callback hell.
😺😺😺
一、为什么需要 Promise 和 async/await?
背景是,JavaScript 是单线程的
JS 在浏览器或 Node.js 中运行时,只能同时做一件事,比如你写了一个网络请求函数 getData(),它一执行就会卡住主线程,页面会“卡死”。
目标:让程序 非阻塞(异步)
我们希望它能“先去请求数据,等结果到了再处理”,而不是“死等”。
二、async/await 是什么?
async/await 是 Promise 的语法糖,让你写异步代码就像写同步代码一样清晰。
举例对比:
用 Promise 写法:
getData().then(data => {
return processData(data);
}).then(result => {
console.log(result);
});
用 async/await 写法:
async function main() {
const data = await getData();
const result = await processData(data);
console.log(result);
}
三、使用场景(超常见)
网络请求 调用接口需要等待返回 fetch()、axios.get()
文件读取 Node.js 读取本地文件 fs.promises.readFile()
动画/定时器 需要延迟执行 setTimeout 封装成 Promise
数据库操作 查询需要时间 db.query()、MongoDB 操作
并发控制 多个请求一起发 Promise.all() 等
四、底层原理简析(简单但关键)
Promise 的本质是一个对象,它有三个状态:
• pending(进行中)
• fulfilled(已成功)
• rejected(已失败)
状态只会从 pending → fulfilled/rejected 一次,不会改变回头路。
const p = new Promise((resolve, reject) => {
resolve(‘OK’);
reject(‘Fail’); // 这句无效
});
事件循环(Event Loop)支持异步:
JS 引擎不会同步执行 .then() 的函数,而是将其放入微任务队列(microtask queue),等当前任务执行完后再运行。
五、常见高级用法(Bonus)
Promise.all:并发执行多个任务,全部成功才成功
await Promise.all([getUser(), getPosts()]);
Promise.race:多个任务,只要一个完成就返回
await Promise.race([timeout(3000), fetchData()]);
😺😺😺Promise 和 async/await 的使用方式
一、Promise 基础语法
- 创建 Promise
const promise = new Promise((resolve, reject) => {
// 异步操作
const success = true;
if (success) {
resolve(‘成功了’);
} else {
reject(‘失败了’);
}
});
- 使用 .then() 和 .catch() 处理结果
promise
.then(result => {
console.log(result); // 成功时打印 ‘成功了’
})
.catch(error => {
console.error(error); // 失败时打印 ‘失败了’
});
二、Promise 的链式调用
doSomething()
.then(result1 => {
return doSomethingElse(result1);
})
.then(result2 => {
return finalStep(result2);
})
.catch(error => {
console.error(‘出错了’, error);
});
三、async/await 的使用方式
async/await 是 Promise 的语法糖,让异步代码更像同步代码,易于理解。
- 声明 async 函数
async function myAsyncFunc() {
return ‘hello’;
}
myAsyncFunc().then(result => console.log(result)); // 打印 hello
- 使用 await 等待 Promise 结果
function fetchData() {
return new Promise(resolve => {
setTimeout(() => resolve(‘数据来了’), 1000);
});
}
async function getData() {
const result = await fetchData();
console.log(result); // 打印 ‘数据来了’
}
getData();
四、try/catch 错误处理
async function getData() {
try {
const result = await fetchData();
console.log(result);
} catch (error) {
console.error(‘出错了’, error);
}
}