获取延期承诺值jQuery



我有以下函数

function commentCount(id) {
var deferred = new $.Deferred()
var url =
_spPageContextInfo.siteAbsoluteUrl +
"/_api/lists/getByTitle('Comments')/items?$select=Id&$filter=ItemID eq " +
id +
" and Title eq 'Colleague'"
getData(url).then(function(data) {
deferred.resolve(data.d.results.length)
})
return deferred.promise()
}

现在我想在HTML字符串中返回该值,如下所示,但它显示[对象对象]

'<div class="card-footer"> <div class="row "><div class="col-lg mobile-center"><a href="#">' + commentCount(item.Id)

我怎样才能获得像那样的价值

您的函数正在返回一个promise,您必须先解决该promise,然后才能获取数据

它还使用了一个不必要的$.Deferred,因为getData()返回了一个promise

需要类似于:

function commentCount(id) {
var url ='....';
// return the getData promise 
return getData(url).then(function(data) {
// return the count to next `then()` in chain
return data.d.results.length
})
}
commentCount(someId).then(function(count){
// do stuff with your html here
var str ='<div> Count:' + count + '</div>';
})

最新更新