【问题标题】:Lightswitch html how to know when async iteration is doneLightswitch html如何知道异步迭代何时完成
【发布时间】:2015-02-26 16:35:46
【问题描述】:

我在另一个异步操作中有一个异步操作。我想知道我怎么知道什么时候一切都完成了。

这是我的代码:

msls.showProgress(msls.promiseOperation(function (operation) {
        screen.Staff.getConfirmedWaiters().then(function (result) {
            result.each(function (item) {
                item.getWaiter().then(function (result) {
                    if (result.Gender == "Female") {
                        confirmedGirls++;
                    }
                });
            });
            operation.complete(confirmedGirls);
        });
    }).then(function (result) {

首先我加载ConfirmedWaiters 集合。完成后,我会迭代每个实体并异步加载一个子实体,所以我想知道迭代何时完成!?但问题是它会立即返回,因为它是异步的,所以我怎么能等到迭代完成然后调用operation.complete()

【问题讨论】:

    标签: html asynchronous visual-studio-lightswitch winjs-promise


    【解决方案1】:

    为了应对这种类型的异步挑战,您需要加入您的承诺。

    以下博客文章提供了有关 Promise 的一些背景知识,对任何 LightSwitch HTML 客户端开发人员都很有用(始终值得牢记的是,LightSwitch HTML 主要基于 WinJS,任何与 WinJS Promise 相关的材料都值得一读):-

    Promises in LightSwitch (Justin Anderson)

    All about promises (for Windows Store apps written in JavaScript)

    根据第二篇博文中介绍的“加入并行承诺”方法,您的代码最终应该类似于以下应该达到预期结果的代码(尽管它可能会遇到性别平等异常 ;-)

    msls.showProgress(msls.promiseOperation(function (operation) {
        screen.Staff.getConfirmedWaiters().then(function (result) {
            var ps = [];
            result.each(function (item) {
                var p = item.getWaiter().then(function (result) {
                    if (result.Gender == "Female") {
                        confirmedGirls++;
                    }
                });
                ps.push(p);
            });
            WinJS.Promise.join(ps).then(function onComplete(result) {
                operation.complete(confirmedGirls);
            }, function onError(error) {
                operation.error(error);
            });
        });
    }).then(function (result) {
    

    希望这可以解决问题。如果没有,上传示例项目以提供更多背景可能会有所帮助。

    【讨论】:

    • @lerner 加入我提出的答案中所涵盖的承诺是否有效?
    • @Lerner 很高兴它有帮助,请您将其标记为答案并将其投票为有用(如果您还没有)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 2020-12-22
    相关资源
    最近更新 更多