我尝试使用jQuery的promise对象来确保在其他代码运行之前我的异步调用已完成。我需要使用Deferred对象,因为我使用SharePoint executeQueryAsync
来运行查询。我正在使用Shereen Qumsieh的例子here。
我的问题是,在结果处理程序中,jQuery承诺总是未定义的,我无法确定原因。有谁之前经历过这个吗?任何帮助或线索指出我正确的方向将非常感激。感谢。
查询
function successCallback() {
console.log(this.d.promise());
this.d.resolve(this.list);
}
function failCallback() {
console.log(this.d.promise());
this.d.reject("something bad happened");
}
function getMyList() {
var d = jQuery.Deferred();
console.log(d.promise());
var clientContext = SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle('Documents');
clientContext.load(list);
var o = {d: d, list:list};
clientContext.executeQueryAsync(Function.createDelegate(o, successCallback), Function.createDelegate(o, failCallback));
return d.promise();
}
结果处理程序
var result = getMyList();
console.log(result);// output: undefined
result.done(function(result) { //TypeError: Cannot read property 'done' of undefined
// result is an SP.List because that is what we passed to resolve()!
var list = result;
console.log('Result done hit. result: ' + result);
});
result.fail(function(result) {
// result is a string because that is what we passed to reject()!
var error = result;
console.log('Result fail hit. result: ' + error);
});
更新
getMyList console.log(d.promise())输出
Object {state: function, always: function, then: function, promise: function, pipe: function…}
successCallback console.log(this.d.promise())输出
Object {state: function, always: function, then: function, promise: function, pipe: function…}
结果处理程序console.log(结果)输出
undefined
带时间戳的顺序输出
getMyList ln 449 Promise output 1412279244379: [object Object]
getMyList ln 458 Promise output 1412279244390: [object Object]
Result output 1412279244392: undefined
Result Handler Error time: 1412279244392: TypeError: Cannot read property 'done' of undefined
successCallback Promise output 1412279244569: [object Object]
successCallback Resolve output 1412279244570: [object Object]
答案 0 :(得分:0)
仍然不确定我的问题的确切根本原因,但我确实找到了解决方案。有两个主要差异使解决方案成为可能。首先,我使用SP.RequestExecutor
代替SP.ClientContext.executeQueryAsync
。然后摆脱@ {Roamer-1888建议的Function.createDelegate()
废话。 SP.ClientContext.executeQueryAsync
一直返回一个从未实际解析过的SP.ClientRequest
对象,而Function.createDelegate
正在使用promise对象做一些奇怪的范围。还不确定那个。
var def = new jQuery.Deferred();
var executor = new SP.RequestExecutor(_spPageContextInfo.siteAbsoluteUrl);
var data = "{ '__metadata': { 'type': 'SP.Data.ListItemEntityTypeFullName' },"
+ "'Title': '" + Title + "',"
+ "'Body': '" + Body+ "'}";
executor.executeAsync({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists(guid'<enter_guid_here>')/items",
method: "POST",
body: data,
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: CsomSuccess,
error: CsomFail
});
function CsomSuccess(result){
def.resolve(result);
}
function CsomFail(data, errorCode, errorMessage){
def.reject('Failed to get host site. Error:' + errorMessage);
}
return def.promise();