我需要运行函数“ testfun 2次”,对于每个函数,我都会有几个名称,比如说testfun(5,global_user)//输出[1,2,4,4,5]和testfun(7,global_user )//输出[9,10,11]
我将运行2个函数后如何将这2个数组放入一个数组中?
testfun(5, global_user);
testfun(7, global_user);
function testfun(groupId, myUser) {
var selectStr = "Title";
var itemsUrl = "https://info.com(" + groupId + ")/users" + "?" + selectStr + "&" + orderbyStr;
var executor = new SP.RequestExecutor;
executor.executeAsync(
{
url: itemsUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: loadTeamNames,
error: errorHandler
}
);
}
var arr = [];
function loadTeamNames(data){
var jsonObject = JSON.parse(data.body);
var results = jsonObject.d.results;
var hide_groups = false;
$(results).each(function(){
var name = $(this)[0].Name;
});
}
谢谢
最佳答案
由于testFun()
使用异步方法,因此您必须在两次运行后立即等待任何实例都无法完成,才能立即执行任何操作。这是使用诺言完成的
您可以使用$when()
并从testFun()
返回承诺。将需要将loadTeamNames
移到testFun
来执行此操作
在两个诺言都得到解决之前,$.when()
不会完成
function testfun(groupId, myUser) {
var defer = $.Deferred();
var selectStr = "Title";
var itemsUrl = "https://info.com(" + groupId + ")/users" + "?" + selectStr + "&" + orderbyStr;
var executor = new SP.RequestExecutor;
executor.executeAsync(
{
url : itemsUrl,
method : "GET",
headers : {"Accept" : "application/json; odata=verbose"},
success : loadTeamNames,
error : errorHandler
}
);
function loadTeamNames(data) {
var jsonObject = JSON.parse(data.body);
var results = jsonObject.d.results;
var hide_groups = false;
$(results).each(function () {
var name = $(this)[0].Name;
});
// resolve deferred and pass data to be used in `$.when()`
defer.resolve(results);
}
return defer.promise;
}
使用
$.when(testfun(5, global_user),testfun(7, global_user)).done(function (results1, results2) {
//do what you need to with arrays results1 & results2
});
在
defer.reject()
中添加errorHandler
关于javascript - JSON循环后推送2个数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35026169/