I would like to ask how to return the data after asynchronous operation when performing asynchronous operation in foreach?

the code is as follows:

function longTimeDo() {
    let data = [];
    let sourse = [1,2,3,4,5];
    sourse.forEach(value=>{
        setTimeout(()=>{
            data.push(value);
        },1000);
    });
    //?data
}
Mar.04,2021

you can use Promise.all or for of plus async/await .

function pushData(arr, value) {
    return new Promise((reslove) => {
        setTimeout(() => {
            arr.push(value);
            console.log('push data over', value)
            reslove();
        }, 1000);
    })
}

async function longTimeDo() {
    let data = [];
    let sourse = [1, 2, 3, 4, 5];

    for (let value of sourse) {
        await pushData(data, value);
    }

    console.log(data)

}

longTimeDo();

this will not work:

function longTimeDo() {
    let data = [];
    let sourse = [1,2,3,4,5];
    sourse.forEach(value => {
        console.log('forEach-star')
        setTimeout(() => {
            data.push(value);
            console.log('forEach-async')
        }, 1000);
        console.log('forEach-end')
    });
    console.log('longTimeDo-end');
}
longTimeDo();

output is
clipboard.png

from the results, we can see that the asynchrony in the loop only acts in the loop, but does not affect the outside of the loop. If you want this function to return the result after asynchronism, it is equivalent to asynchronously changing Synchronize, then you need to use Primise

.
async function longTimeDo () {
    let data = [];
    let sourse = [1,2,3,4,5];
    let allP = sourse.map(value => {
        return new Promise((res, rej) => {
            setTimeout(() => {
                data.push(value+1);
                res(data)
            }, 1000);
        });
    });
    await Promise.all(allP);

    return data;
}
longTimeDo().then(res => {
    log(res) // [2, 3, 4, 5, 6]
})
The most low way of

is to add a count, num=0;settimeout to add 1 at a time, and to judge return data when num==source.length

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e50fd1-450e5.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e50fd1-450e5.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?