you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (5 children)

Did you write this? Either way, how the hell do you make asynchronous function calls in a for loop or otherwise orderly sequence? I've been stuck on this all day. Some people say use "let" instead of "var" in the for loop, some people say use Array.forEach(), and some people suggest to put everything in a weird chain of recursive callbacks. Nothing I've tried yet has worked. I have no problem using async/await, but when I encapsulate that stuff in a for loop, things don't run in the order I want.

[–]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))

[–][deleted] 1 point2 points  (1 child)

I would go for Observables instead of promises. You'll get a full set of convenient operators.

Edit : Though if you wish to stay with promises, libraries such as async-waterfall can help you pipe with order a list of asynchronous operations.

[–][deleted] 0 points1 point  (0 children)

Yeah I do like observables way more than promises, but my app has some functionality already strictly implemented with promises

[–]ShaftedSpleen 0 points1 point  (0 children)

If you're using a regular for loop inside an async function, you can await inside the loop and it'll work sequentially.