es6的async await的控制并发,简化错误处理,链式调用

1 篇文章 0 订阅
1 篇文章 0 订阅

1.与高阶函数结合使用

// 异步过滤函数
async function asyncFilter(array, predicate) {
    const results = await Promise.all(array.map(predicate));

    return array.filter((_value, index) => results[index]);
}

// 示例
async function isOddNumber(n) {
    await delay(100); // 模拟异步操作
    return n % 2 !== 0;
}

async function filterOddNumbers(numbers) {
    return asyncFilter(numbers, isOddNumber);
}

filterOddNumbers([1, 2, 3, 4, 5]).then(console.log); // 输出: [1, 3, 5]


2.优化递归

// 异步递归函数
async function asyncRecursiveSearch(nodes) {
    for (const node of nodes) {
        await asyncProcess(node);
        if (node.children) {
            await asyncRecursiveSearch(node.children);
        }
    }
}

// 示例
async function asyncProcess(node) {
    // 对节点进行异步处理逻辑
}


3.异步初始化类实例

class Example {
    constructor(data) {
        this.data = data;
    }

    static async create() {
        const data = await fetchData(); // 异步获取数据
        return new Example(data);
    }
}

// 使用方式
Example.create().then((exampleInstance) => {
    // 使用异步初始化的类实例
});



4.控制并发数

async function asyncPool(poolLimit, array, iteratorFn) {
    const result = [];
    const executing = [];

    for (const item of array) {
        const p = Promise.resolve().then(() => iteratorFn(item, array));
        result.push(p);

        if (poolLimit <= array.length) {
            const e = p.then(() => executing.splice(executing.indexOf(e), 1));
            executing.push(e);
            if (executing.length >= poolLimit) {
                await Promise.race(executing);
            }
        }
    }

    return Promise.all(result);
}

// 示例
async function uploadFile(file) {
    // 文件上传逻辑
}

async function limitedFileUpload(files) {
    return asyncPool(3, files, uploadFile);
}


5.链式调用

class ApiClient {
    constructor() {
        this.value = null;
    }

    async firstMethod() {
        this.value = await fetch('/first-url').then(r => r.json());
        return this;
    }

    async secondMethod() {
        this.value = await fetch('/second-url').then(r => r.json());
        return this;
    }
}

// 使用方式
const client = new ApiClient();
const result = await client.firstMethod().then(c => c.secondMethod());


6.简化错误处理

async function asyncOperation() {
    try {
        const result = await mightFailOperation();
        return result;
    } catch (error) {
        handleAsyncError(error);
    }
}

async function mightFailOperation() {
    // 有可能失败的异步操作
}

function handleAsyncError(error) {
    // 错误处理逻辑
}

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ifHappyEveryDay@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值