JS中的async与await
- 其他
- 2025-08-05 11:54:01

课程地址
有 4 个返回 Promise 对象的函数 ABCD,现在想让这 4 个 Promise 顺序执行:
const isA = true; const isB = true; const isC = true; const isD = true; function A() { return new Promise((resolve, reject) => { console.log("running A"); setTimeout(() => { if (isA) { resolve("A success"); } else { reject("A fail"); } }, 1000); }); } function B() { return new Promise((resolve, reject) => { console.log("running B"); setTimeout(() => { if (isB) { resolve("B success"); } else { reject("B fail"); } }, 1000); }); } function C() { return new Promise((resolve, reject) => { console.log("running C"); setTimeout(() => { if (isC) { resolve("C success"); } else { reject("C fail"); } }, 1000); }); } function D() { return new Promise((resolve, reject) => { console.log("running D"); setTimeout(() => { if (isD) { resolve("D success"); } else { reject("D fail"); } }, 1000); }); } 方法一前一个 Promise 的 then 返回下一个 Promise 实例,然后链式调用 then
A().then( (res) => { console.log(res); return B(); } ).then( (res) => { console.log(res); return C(); } ).then( (res) => { console.log(res); return D(); } ).then( (res) => { console.log(res); } ); 方法二使用 async 和 await:
async 函数是使用async关键字声明的函数。async 函数是 AsyncFunction 构造函数的实例,并且其中允许使用 await 关键字。async 和 await 关键字让我们可以用一种更简洁的方式写出基于 Promise 的异步行为,而无需刻意地链式调用 promise
await 操作符用于等待一个 Promise 兑现并获取它兑现之后的值。它只能在 async 函数或者模块顶层中使用
await 可以让异步的操作获得同步的写法
async function ABCD() { const resA = await A(); // 同步的写法,但实际上是异步的 console.log(resA); const resB = await B(); console.log(resB); const resC = await C(); console.log(resC); const resD = await D(); console.log(resD); } ABCD();JS中的async与await由讯客互联其他栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“JS中的async与await”
上一篇
栈和队列的动态实现(C语言实现)
下一篇
数据预处理技术之数据归一化