使异步功能以同步方式运行-Javascript

时间:2019-02-06 11:08:21

标签: javascript angularjs asynchronous promise

这是我的问题:

我的主要功能:

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函数:

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

openTab函数:

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

输出:

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

'handleOpenTab function working'
'handleOpenTab function working'

我的预期输出:

'openReport working'
'handleOpenTab function working'

'openReport working'
'handleOpenTab function working'

如何实现?我无法在我的forEach函数中使用异步等待,因为使用的是旧节点版本。

如果有可能使用async / await解决此问题,我将尝试升级我的节点版本。

1 个答案:

答案 0 :(得分:0)

使用诺言,可能看起来像这样:

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);
};