A better way to fire off a sequence of the same pr

2019-09-13 06:25发布

问题:

the below code uses a when sequence to fire off a sequence of the same promise but passing in slightly different data.

when/sequence accepts a single common set of arguments for the entire sequence the same going to each. So I "tricked" it by closing on the index that instance/element will need inside a function calling the promise and then had that function grab the index needed for that promise when the function is called for that element.

This all works I am just wondering if there is some package method out there, or I can modify my pTasker or otherwise deal with different inputs to a set of promises in a more robust/general way.

I thought maybe make an array of "copies" of the input argument and then the enclosed function can grab the appropriate one from the array although that doesn't change much the enclosed function still needs to know which iterate it is. Any experts out there have a better/best way to skin this cat, or is this as good as it gets?

  let cmds = args.components.map( i => {
        return args => {
            let cmpt = i-1;
            args.component = args.components[cmpt];
            Debug.L1('cmpt, component',cmpt, args.component)
            return device.cmd(args)
        }
       });

return _.pTasker(cmds, args)
    .then(cmds => {
        console.log('all responses ', cmds.map(cmd => {
            return cmd.response
        }))
        resolve()
    })
    .catch(function(e) {
        console.log('error: ', e)
        reject(e)
    })

and the promise sequence builder

const fs = require('fs'),
    sequence = require('when/sequence'),
    parallel = require('when/parallel'),
    node = require('when/node');

// Lift fs.readFile so it returns promises
let readFile = node.lift(fs.readFile);

let self = module.exports = {

    // Run an array of "tasks" in sequence as promises, embedded array will be treated as running in parallel
    pTasker: function(tasks, data) {

        return sequence(
            tasks.map(function(item) {
                if (Array.isArray(item)) {
                    return data => parallel(item, data)
                } else {
                    return item
                }
            }), data)
    },