DEV Community

Discussion on: Don’t use for loop for JavaScript Arrays

Collapse
 
aminnairi profile image
Amin • Edited

This is because you are returning an array of pending promises. If you want to fulfill these promises, you can use Promise.all. And if you want the result, you must await the resolution of Promise.all. Or you can also use .then.

function sleep(seconds: number) {
    return new Promise(function(resolve) {
        setTimeout(resolve, 1000 * seconds);
    });
}

function increment(input: number) {
    return input + 1;
}

async function main() {
    const nums = await Promise.all([1, 2, 3, 4, 5].map(async (num) => {
        await sleep(1);

        return increment(num);
    }));

    console.log(nums);
    // [ 2, 3, 4, 5, 6 ]
}

main();

Some comments have been hidden by the post's author - find out more