当前位置: 首页 > news >正文

JS 中的 async 与 await

课程地址

有 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();

相关文章:

  • Git基础
  • uniapp开发过程一些小坑
  • 认识数学建模
  • linux bash shell的getopt以及函数用法小记
  • 携程基于Jira Cloud的敏捷项目管理实践
  • EXCEL VBA获取幸运数字号码
  • Sentinel降级操作
  • 数据预处理技术之数据归一化
  • k8s中netty服务器容器tcp连接数量优化
  • Sentinel-1 扩展时序注释数据集 (ETAD)的查询和下载
  • Android 基于Fragment的权限封装
  • ASP.NET Core NE8实现HTTP Upgrade和HTTP CONNECT代理服务器
  • php/js:实现几秒后进行页面跳转
  • 【软考中级】3天擦线过软考中级-软件设计师
  • 使用vscode查bug
  • 几款提高开发效率的Idea 插件
  • 力扣题目训练(1)
  • c++ class总结
  • 微认证 openEuler社区开源贡献实践
  • 头歌C语言递归函数、嵌套函数
  • 印控克什米尔地区再次传出爆炸声
  • 乌外长:乌方准备无条件停火至少30天
  • 中国海外发展:今年前4个月销售665.8亿元,花费305亿元拿地
  • 上海第四批土拍成交额97亿元:杨浦宅地成交楼板单价半年涨近7000元
  • 国家主席习近平同普京总统出席签字和合作文本交换仪式
  • 甘怀真:天下是神域,不是全世界