首页 > 解决方案 > JS:处理列表时的“前”和“后”操作(使用 IIFE ?)

问题描述

考虑以下将“列表”作为参数并相应地对数组执行操作的代码:

# ready to test: just copy it in a file...
const create = (list) => {
    console.log('seting up for list', list)

    const install = (pool) => console.log('installing', pool)
    const nope = (pool) => void 0
    const action = (t) => console.log('action', t)  

    const api = (tasks) => {
        return {
            install: (pool) => {
                tasks.install(pool)

                // the TURN is structurally made HERE (no if...)
                tasks = { install: nope }

                return { action }       
            }
        }
    }

    let once = { install }

    return api(once)
}   


const bmp = { 'blocks-memoty-pool':  1234 }
const lists = ['a,b,c', 'd,e,f']
const arr = [0, 1, 2, 3]

lists.map((l) => {
    console.log()
    const created = create(l)

    arr.map((e) => {        
        created.install(bmp).action(e)
    })
})

在这里,“安装”操作在开始时仅触发一次。'列表' 并且仅在处理数字数组'arr'的开始时应用一次。

有没有办法使用 IIFE 来抽象“一次”行为?

我们能否以同样的方式进行 endong 安装后任务?

注意:这个问题是关于处理的“方面”。因为它将适用于 Async/Await 用例.. 我必须避免这样的事情:

for(let i = 0; i < arr.length; i++) {
    if(i === 0) pre_install(nmp)
    process(arr[i])
    if(i === arr.length - 1) post_install(nmp)       
}

因为循环中的测试成本(就复杂性而言)......

问候。

标签: javascriptsimplifyiifeaspect

解决方案


推荐阅读