链式调用和延迟执行
作者:xie392地址:https://v.douyin.com/ieaCTbNF/更新时间:2024-12-21
案例代码
1function arrange(name) {2// 任务队列3const tasks = []45// 添加任务6tasks.push(() => {7console.log(`${name} is notified`)8})910function doSomething(action) {11tasks.push(() => {12console.log(`Start to ${action}`)13})14return this15}1617function wait(sec) {18tasks.push(() => new Promise(resolve => {19setTimeout(resolve, sec * 1000)20}))21return this22}2324function waitFirst(sec) {25// 在任务队列的最前面插入一个任务26tasks.unshift(() => new Promise(resolve => {27setTimeout(resolve, sec * 1000)28}))29return this30}3132async function execute() {33for (const t of tasks) {34await t()35}36}3738return {39do: doSomething,40wait: wait,41waitFirst: waitFirst,42execute: execute43}44}454647arrange('William').execute()48// > William is notified495051arrange('William').do('commit').execute()52// > William is notified53// > Start to commit545556arrange('William').wait(5).do('commit').execute()57// > William is notified58// 等待5秒59// > Start to commit6061arrange('William').waitFirst(5).do('commit').execute()62// 等待5秒63// > William is notified64// > Start to commit
输出结果:
1William is notified2William is notified3William is notified4Start to commit5William is notified6Start to commit7Start to commit
目录