使用带有循环和嵌套函数的Promise

时间:2016-08-08 18:32:20

标签: javascript rest loops promise nested-loops

我试图在这些循环中使用带有循环和嵌套函数的promises。我有一系列函数可以从REST调用中恢复SharePoint列表项 - 一旦完成执行,然后调用另一个函数来使用返回的数据。

由于存在多个列表,并且随后在每个列表中有多个列表项,因此我使用while循环来进行每个REST调用,并从那里将数据(列表项)放入对象中。这些对象被放入一个数组中,这就是第二个函数继续使用的内容。

我无法收到承诺的回复。我想要将多个promises推送到数组,最后使用Promise.all查看在使用then之前是否已解决所有问题。问题是所有承诺都保留pending,因为我没有正确返回resolve。请参阅下文。

    function onQuerySuccess(sender, args) {
        var itemEnumerator = items.getEnumerator();

        while (itemEnumerator.moveNext()) {
            var promise = new Promise(function (resolve, reject) {
                var item = itemEnumerator.get_current();
                item = item.get_item('URL');
                var itemUrl = item.get_description();

                getRequestItemsFromList(itemUrl);
            });

            promises.push(promise); // all promises are present, but their status is pending
        }

        console.log(promises);

        Promise.all(promises).then(function (val) {
            console.log(val);
            execFuncs(); // function to execute once all the above are done
        }).catch(function (response) {
            console.log(response);
        });
    }

因为涉及很多功能,所以这是执行顺序:

getRequestItemsFromList //gets url for each list
execCrossDomainRequest (on success call) // makes REST call to get list and its items
cleanData // trims data and puts it in objects

最后一个是我认为我打电话给Promise.resolve()的地方,因为这是该行的结尾。

无论哪种方式,这都行不通。我检查了其他线程,但我试图这样做而不使用任何库。提前致谢。

修改

完整相关代码:

var promises = [];

window.requests = [];

function getRequestLists() {
    var requestsLists = hostWeb.get_lists().getByTitle('Name');  // sharepoint list with all the request list urls.
    context.load(requestsLists);

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View></View>');
    var items = requestsLists.getItems(camlQuery);

    context.load(items, 'Include(URL)');

    context.executeQueryAsync(onQuerySuccess, onQueryFail);

    function onQuerySuccess(sender, args) {
        var itemEnumerator = items.getEnumerator();

        while (itemEnumerator.moveNext()) {
            var promise = new Promise(function (resolve, reject) {
                var item = itemEnumerator.get_current();
                item = item.get_item('URL');
                var itemUrl = item.get_description();

                getRequestItemsFromList(itemUrl);
            });

            promises.push(promise);
        }

        console.log(promises);

        Promise.all(promises).then(function (val) {
            console.log(val);
            execFuncs(); // not shown here
        }).catch(function (response) {
            console.log(response);
        });
    }

    function onQueryFail(sender, args) {
        alert("Request to retrieve list URL items has failed. " + args.get_message());
    }
}

function getRequestItemsFromList(url) {
    var lastPos = getSubstringIndex(url, "/", 4);
    var webUrl = url.substring(0, lastPos); // truncates list url to parse out web url       

    var absListPos = getSubstringIndex(url, "AllItems.aspx", 1);
    var absListUrl = url.substring(0, absListPos); // truncates the AllItems.aspx at the end of the list url

    var relListPos = getSubstringIndex(absListUrl, "/", 3);
    var relListUrl = absListUrl.substring(relListPos, absListUrl.length); // gets the list's relative url 

    var listName = "List Name";

    console.log(webUrl);
    execCrossDomainRequest(webUrl, listName, absListUrl);
}

function execCrossDomainRequest(webUrl, listName, absListUrl) {
    var executor = new SP.RequestExecutor(appWebUrl);

    executor.executeAsync({ // to collect the list description
        url: appWebUrl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle(@name)?" +
            "@target='" + webUrl + "'&@name='" + listName + "'" +
            "&$select=Description",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: onCallSuccess,
        error: onCallFail
    });

    function onCallSuccess(data) {
        var json = JSON.parse(data.body);
        var description = json.d.Description;

        executor.executeAsync({ // to collect the list item information
            url: appWebUrl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle(@name)/items?" +
                "@target='" + webUrl + "'&@name='" + listName + "'" +
                "&$top=500&$select=*," +
                "Assigned_x0020_To/Title" +
                "&$expand=Assigned_x0020_To/Id",
            method: "GET",
            headers: { "Accept": "application/json; odata=verbose" },
            success: onItemsCallSuccess,
            error: onItemsCallFail
        });

        function onItemsCallSuccess(data) {
            var itemsJson = JSON.parse(data.body);
            var results = itemsJson.d.results;

            cleanData(results, description, absListUrl);
        }

        function onItemsCallFail(data, errorCode, errorMessage) {
            console.log("Could not make list items cross domain call. " + errorMessage);
        }
    }

    function onCallFail(data, errorCode, errorMessage) {
        console.log("Could not make list cross domain call. " + errorMessage);
    }
}

function cleanData(results, listDescription, absListUrl) {

    if (!results.length) {
        return;
    }

    for (var i = 0; i < results.length; i++) {
        var client = listDescription;
        var id = results[i].ID;
        ...

        }

        var request = new Request(client, id, path, title, status, estimated, assignedTo, priority, description, response);

        window.requests.push(request);
    }

    return Promise.resolve();
}

2 个答案:

答案 0 :(得分:2)

使用这样的promise构造函数时:

var promise = new Promise(function (resolve, reject) {

这意味着在此区块中的某个位置,您正在调用resolve和/或reject来解决承诺。

但是你永远不会这样做,让创建的promise对象永远处于暂挂状态。

请参阅Constructing a promise

答案 1 :(得分:0)

在我看来你的promises数组没有定义:do var promises = [];在你的while循环之前。