Lightswitch html how to know when async iteration is done

人走茶凉 提交于 2019-12-08 03:36:37

问题


I have an async operation inside another async operation. I wonder how can i know when everything is done.

Here is my code:

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) {

First I load the ConfirmedWaiters collection. Once it is completed I iterate every entity and load a child entity async, so I want to know when the iteration is complete!? but the problem is that its returning right away because its async so how can I wait till the iteration is complete and then call operation.complete()?


回答1:


In order to tackle this type of asynchronous challenge, you need to join your promises.

The following blog posts provide some background on promises and are a useful read for any LightSwitch HTML Client developer (it's always worth bearing in mind that LightSwitch HTML is largely WinJS based and any WinJS promise related material is worth reading): -

Promises in LightSwitch (Justin Anderson)

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

Based on the 'Joining parallel promises' approach covered in the second of these blog posts, your code should end up similar to the following which should achieve the desired result (though it may encounter a Gender Equality Exception ;-)

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) {

Hopefully this should do the trick. If not, uploading a sample project to provide more background may help.



来源:https://stackoverflow.com/questions/28747793/lightswitch-html-how-to-know-when-async-iteration-is-done

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!