一个小插件. 微信小程序线程等待模块.

336 阅读1分钟
var threadHandler = []
var waitHandler = {}
var index = 0
function Action(threadFunc) {
    var threadName = 'default';
    var tid = threadName + (new Date() - 0) + (index++)
    var threadObj = {
        id: tid,
        name: threadName,
        run: function (cb) {
            cb && cb(threadObj)
        },
        waitAll: function (cb) {
            threadHandler.filter(function (item) {
                return item.id == tid
            })[0].status = 1
            waitHandler[threadObj.name] = function () {
                cb && cb(threadObj)
            }
        },
        end: function () {
            threadHandler.filter(function (item) {
                return item.id == tid
            })[0].status = 1
            threadObj.checkWaitHandler()
        },
        checkWaitHandler: function () {
            var isAllEnd = threadHandler.every(function (item) {
                return item.status == 1
            })
            isAllEnd && waitHandler[threadObj.name]();
        }
    }
    threadHandler.push({
        name: threadName,
        id: tid,
        status: 0
    })
    threadFunc(threadObj)

}
Action(thread => {
    thread.run(seed => {
        setTimeout(() => {
            console.log('11')
            seed.end();
        }, 1600)
    });
})

Action(thread => {
    thread.run(seed => {
        setTimeout(() => {
            console.log('22')
            seed.end();
        }, 1200)
    });
})
Action(thread => {
    thread.waitAll(() => {
        console.log(33)
    });
}) 


我的使用场景是 需要下载多个图片到本地, 然后当全部执行完成后, 画到canvas上