【问题标题】:Make asynchronous function to run as synchronous - Javascript使异步函数同步运行 - Javascript
【发布时间】:2019-02-06 21:37:25
【问题描述】:

这是我的问题:

我的主要功能:

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 来解决这个问题,我会尝试升级我的节点版本。

【问题讨论】:

  • 你需要使用 Promise。你的旧节点版本仍然支持 Promises,对吧?
  • 对每个 ajax 调用使用时间戳,并包含与选项参数相同的内容。收到回复后与时间戳进行交叉检查
  • @TKoL 哪个函数需要转换为 promise?
  • 如何使用 async/await 来解决这个问题?如果我找到解决方案,我将升级节点版本。
  • @MohamedSameer 您的 OpenReport 函数说它执行 ajax 调用和其他操作,因此该函数应该返回一个在 ajax 调用完成和 this.openTab 被调用后解析的承诺。然后你必须调整 mainFunction 来使用 Promise,我个人会使用递归循环

标签: javascript angularjs asynchronous promise


【解决方案1】:

使用 Promise,它可能看起来像这样:

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

【讨论】:

  • 如果没有其他选择,这将无济于事。我假设你在谈论我的 mainFunction,所以我希望看到如何在没有反模式的情况下实现相同的循环和等待能力。
  • 我已编辑为仅使用承诺链的版本
  • 我认为它可能看起来像那样,不确定。
猜你喜欢
  • 2021-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-05
  • 1970-01-01
  • 2012-02-25
  • 2020-07-26
相关资源
最近更新 更多