简体   繁体   中英

Make asynchronous function to run as synchronous - Javascript

Here is my problem:

My main function:

const mainFunction = () => {
    const reports = JSON.parse($sessionStorage.datas);
    // reports contains array of objects.
    // consider i have two objects inside one array, so the loop will execute two times now
    reports.forEach((item) => {
        this.openReport(item);
    });
};
mainFunction();

openReport function:

this.openReport = (report)  => {
    console.log('openReport working');
    // some async functions will be here
    // ajax calls
    this.openTab(report);
};

openTab function:

this.openTab = (report) => {
    console.log('handleOpenTab function working');
}

Output:

// Now i have two objects, so forEach works two times.
'openReport working'
'openReport working'

'handleOpenTab function working'
'handleOpenTab function working'

My expected output :

'openReport working'
'handleOpenTab function working'

'openReport working'
'handleOpenTab function working'

How to achieve this? i am unable to use async await inside my forEach function, because using old node version.

If its possible to use async/await for this problem, i will try to upgrade my node version.

Using promises, it would look something like this probably:

this.openReport = (report) => {
    console.log('openReport working');
    // some async functions will be here
    // ajax calls
    return new Promise(function(resolve, reject) {
        ajaxCall('url', resolve); // reject as necessary!
    }).then(answer => {
        this.openTab(report);
        return answer;
    });
};

const mainFunction = () => {
    const reports = JSON.parse($sessionStorage.datas);
    // reports contains array of objects.

    function getNextReport(index) {
        if (index >= reports.length) return Promise.resolve();
        let item = reports[index];
        return this.openReport(item).then(function(answer) {
            // do something with answer
            return getNextReport(index+1);
        });
    }

    return getNextReport(0);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM