在一段时间内嵌套的承诺不能同步工作

时间:2015-07-14 08:31:47

标签: javascript sharepoint asynchronous promise project-server

我正在用javascript编写一个SharePoint应用程序(用于Project Server),我使用异步调用来查询来自服务器的数据。

这些异步调用依赖于彼此,甚至是循环。

要了解问题:

Project Server上有多个项目。我想阅读每个项目。然后我逐个完成项目并阅读他们的属性。它会是这样的:

$(document).ready(function () {
    projContext = PS.ProjectContext.get_current();

    //I read all the projects when the page loads
    var projectspromise = GetAllProjects();
    projectspromise.done(function (resultprojects) {
        //if I get the data i use the result in the next function
        GoThroughProjects(resultprojects);
    });

    projectspromise.fail(function (result) {
        var error = result;
    console.log(error);
    });

});

function GoThroughProjects(projectlist) {
    var projenum = projectlist.getEnumerator();
    while (projenum.moveNext()) { //i'm going through the projects one by one
        var project = projenum.get_current();
        alert("Y - " + project.get_name()); //Y ALERT

        GetProperties(project).then(
            function (resultproperties) {
                alert("X - Got the properties"); //X ALERT
            },
            function (sender, args) {
                alert(args.get_message());
            }
       );
   }
}

在这个例子中,我将按顺序收到警报,这对我来说不太合适。 以 Y 开头的警报会一个接一个地显示,中间没有任何X警报。 (所以如果有3个项目,它们会像YYYXXX一样,例如代替YXYXYX)。

我如何链接它们,以便它们以更加同步的方式运行?

所以在某种伪代码中它就像是:

First Async Call to read all projects
for each project
{
    Second Async Call to read the selected projects data
    for each property
    {
        do something with it / maybe third level of async call
    }
}

0 个答案:

没有答案