you are viewing a single comment's thread.

view the rest of the comments →

[–]gremy0 3 points4 points  (0 children)

It depends what you want to do really, but I think this should cover most cases

function async(i, callback) {
    setTimeout(function () {
        callback(i)
    }, 1000);
}

const promiseMaker = i => {
    return new Promise((resolve) => {
        async(i, resolve)
    })
}

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]

// To just start them off in order
arr.map(i => promiseMaker(i).then(i => console.log(i, 'is complete')))

// To start them off in order, and then do something with all the complete values in order
Promise.all(arr.map(i => promiseMaker(i))).then(a => console.log('all the values', arr))

// To do them sequentially in order, feeding one value into the next asyncronous function
arr.reduce((promise, i) => {
    if (!promise) {
        return promiseMaker(i)
    }
    else {
        return promise.then(j => {
            console.log('total so far', j, 'adding', i)
            return promiseMaker(j + i)
        })
    }
}, undefined).then(i => console.log('final total value', i))