从第二个函数返回字符串

时间:2014-05-20 08:29:50

标签: javascript sharepoint

我已经创建了一个返回图片网址的函数。
见下面的代码:

function loadAttachment(itemid) {
    web = context.get_web();
    attachmentFolder = web.getFolderByServerRelativeUrl("Lists/LijstMedewerkers/Attachments/" + itemid);
    attachmentFiles = attachmentFolder.get_files();
    //Load attachments
    context.load(attachmentFiles);
    context.executeQueryAsync(onLoaddAttachmentSuccess, onLoadAttachmentFail);
    alert(picture);
    return picture;
}

function onLoadAttachmentFail(sender, args) {
    alert('Failed to get lists items. Error:' + args.get_message());
}

function onLoaddAttachmentSuccess(sender, args) {
    // Enumerate and list the Asset Attachments if they exist
    var attachementEnumerator = attachmentFiles.getEnumerator();
    while (attachementEnumerator.moveNext()) {
        var attachment = attachementEnumerator.get_current();
        picture = attachment.get_serverRelativeUrl();
    }
}

好吧,它没有返回图片的价值。当我发出警报时,我会看到价值但是返回时它不起作用。即使我把图片放在itemid中。

知道我做错了吗?

1 个答案:

答案 0 :(得分:0)

由于SP.ClientContext.executeQueryAsync method async

SP.ClientContext.executeQueryAsync(succeededCallback, failedCallback) 

succeededCallback用于声明包含返回结果的函数。

使用JSOM等异步API时,通常会使用以下模式:

  • 使用嵌套回调
  • 使用承诺模式

以下示例演示了如何使用回调方法检索附件文件:

function loadAttachments(listTitle, itemId,success,error) {
   var context = new SP.ClientContext.get_current();
   var web = context.get_web();
   var list = web.get_lists().getByTitle(listTitle);
   var listItem = list.getItemById(itemId);
   var files = listItem.get_attachmentFiles();
   context.load(files);
   context.executeQueryAsync(function(){
     success(files);
    }, 
    error);
}

用法

获取第一个文件附件网址

loadAttachments('Projects',3,
function(attachmentFiles){
    if(attachmentFiles.get_count() > 0) {
       var attachmentFile = attachmentFiles.getItemAtIndex(0);
       var fileUrl = attachmentFile.get_serverRelativeUrl();
       //...
    }
},
function(sender,args){
   console.log(args.get_message()); 
});