Javascript 在继续之前等待结果

标签 javascript executequery

我是 Javascript 的新手,在我会走路之前尝试运行,但我必须产生一个结果,所以我来了。

我以为我已经在另一个问题中找到了这个问题的答案,但它并没有像预期的那样对我有用,下面是我的脚本,它的功能是查看 SharePoint 列表并将一些值返回到 3 个数组中,然后我使用这些数组提供数据来完成一些图表数据。

                    <script>
                    // load all necessary sharepoint javascript libaries
                    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {

                        // load the sharepoint list.
                        loadSharepointList();
                    });
                    var arrPlan = new Array()
                    var arrActual = new Array()
                    var arrMonth = new Array()


                    // loads the sharepoint list
                    function loadSharepointList() {

                        // create the sharepoint content.
                        var context = SP.ClientContext.get_current();

                        // get the list by the title.
                        var list = context.get_web().get_lists().getByTitle('Package');

                        // create the query.
                        var caml = new SP.CamlQuery();
                        caml.set_viewXml(''); 

                        // get the list items asynchronously
                        var listItems = list.getItems(caml);
                        context.load(listItems , 'Include(Title,Month,Plan,Actual)');
                        context.executeQueryAsync(

                            // success delegate
                            Function.createDelegate(this, function() {

                            // loop through the items.
                                var listEnumerator = listItems.getEnumerator();
                                while (listEnumerator.moveNext()) {

                                    // get the current list item.
                                    var listItem = listEnumerator.get_current();

                                    // get the field value.
                                    var titleValue = listItem.get_item('Month');
                                    var monthValue = listItem.get_item('Month');
                                    var planValue = listItem.get_item('Plan');
                                    var actualValue = listItem.get_item('Actual');
                                    //alert(monthValue);
                                    arrPlan.push(planValue);
                                    arrActual.push(actualValue);
                                    arrMonth.push(monthValue);
                                    //alert(arrMonth);

                                }

                            }),

                            // error delegate
                            Function.createDelegate(this, function() {
                                alert('Error fetching data from Sharepoint!');      
                            }));

                    }

                            //var labels = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October"];
                            var netpphcanvas = document.getElementById("pphchart");
                            var planData = {
                                label: 'Plan',
                                fill: false,
                                data: [1.06,1.58,1.74,1.62,1.50,1.37,1.36,1.44,1.84,1.76],
                                backgroundColor: 'rgba(133, 133, 133, 1)',
                                borderColor: 'rgba(133, 133, 133, 1)',
                                borderWidth: 3,
                                yAxisID: "y-axis-region"
                            };
                            var actualData = {
                                label: 'Actual',
                                fill: false,
                                data: [1.37,1.65,1.84, 1.78,1.55, 1.74,1.57, 1.74,1.90,1.63],
                                backgroundColor: 'rgba(99, 132, 0, 0.6)',
                                borderColor: 'rgba(99, 132, 0, 0.6)',
                                borderWidth: 3,
                                yAxisID: "y-axis-region"
                            };
                            //********This is the part I am using for testing
//***********
                            var netpphData = {
                                //labels: labels,
                                labels: arrMonth,
                                datasets: [planData,actualData]
                                            };
                            var netdelOptions = {
                            scales: {
                                xAxes: [{
                                    barPercentage: 1,
                                    categoryPercentage: 0.6
                                }],
                                yAxes: [{
                                    id: "y-axis-region"
                                }]
                            },
                            elements: {
                                line: {
                                    tension: 0, // disables bezier curves
                                }
                            },
                            title: {
                                display: true,
                                text: 'Net-Delivered PPH',
                                fontSize: 12
                            },
                            legend: {
                                display: true,
                                labels: {
                                    fontColor: '#000',
                                    fontSize: 12
                                }
                            }


                        };

                        var lineChart = new Chart(netpphcanvas, {
                            type: 'line',
                            data: netpphData,
                            options: netdelOptions
                        });
                    </script>

我正在尝试使用返回的数组来完成图表的数据和标签部分,为了对此进行测试,我从月度数据开始,该数据在这部分代码中检索...

context.executeQueryAsync(

                        // success delegate
                        Function.createDelegate(this, function() {

                        // loop through the items.
                            var listEnumerator = listItems.getEnumerator();
                            while (listEnumerator.moveNext()) {

                                // get the current list item.
                                var listItem = listEnumerator.get_current();

                                // get the field value.
                                var titleValue = listItem.get_item('Month');
                                var monthValue = listItem.get_item('Month');
                                var planValue = listItem.get_item('Plan');
                                var actualValue = listItem.get_item('Actual');
                                //alert(monthValue);
                                arrPlan.push(planValue);
                                arrActual.push(actualValue);
                                arrMonth.push(monthValue);
                                //alert(arrMonth);

                            }

                        }),

我已经使用 alert 方法验证了它的有效性,它确实将月份返回到名为 arrMonth 的数组中

但是,脚本的其余部分似乎在访问此数据源和填充 arrMonth 之前运行。

我还通过使用另一个名为标签的数组并手动归档它来检查它,它工作正常。

我以为是因为获取数据的函数被异步调用了

context.executeQueryAsync(

但是,我将其更改为 context.executeQuery( 并且仍然得到与检索数据之前页面加载相同的结果

显然,我遗漏了一些东西,如果有任何帮助,我将不胜感激

亲切的问候 德里克

最佳答案

您需要链接 promise 以确保所有这些按顺序运行。

这两个链接将帮助您:

A synchronous Breeze ExecuteQuery

What does the function then() mean in JavaScript?

这是关于 promise 链的有用教程。 https://javascript.info/promise-chaining

关于Javascript 在继续之前等待结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53410110/

相关文章:

javascript - 使用带有标签 :true, 的 select2 jquery 插件,如何防止选项显示在已选择的下拉列表中?

java - 使用 MySQL 从 Java 中的多个表中选择带前缀的列

java - 获取 TDS 驱动程序 - java.lang.NullPointerException。这个异常不一致

c# - 如何在 LINQ-TO-SQL 中映射来自 ExecuteQuery() 的额外字段但保留 LINQ 实体

javascript - rails 4 : Turbolinks redirect with flash

javascript - 返回数组中的特定对象值

javascript - 解析 Highcharts 的 JSON 数据

javascript - 单击元素的 jQuery 多个背景

sqlite - SQLite x86中的ExecuteQuery命令运行非常慢

sql - H2中通过PreparedStatement查询抛出异常: This method is not allowed for a prepared statement; use a regular statement instead