A
A
Anton Anton2017-02-16 11:50:08
JavaScript
Anton Anton, 2017-02-16 11:50:08

How to correctly process an array with an asynchronous function call?

I'm trying to deal with promise and calling an asynchronous function in a loop.
Can't make reduce result in a promise that should be executed at the very end

arr = [1,2,3,4,5];

function timeout(val){
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{
            console.log(val);
            resolve();
        }, 500);
    });
}

arr.reduce((prev, curr, index, arr)=>{
    return prev.then((res)=>{
        return timeout(curr);
    });
}, Promise.resolve())
        .then(console.log('res'));

for some reason, it displays res at the beginning, and then the contents of the array:
res
1
2
3
4
5

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aves, 2017-02-16
@Fragster

You need to pass the function as an argument to the then method, () => console.log('res')orconsole.log.bind(console, 'res')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question