Javascript:如何获得返回值

时间:2018-02-27 12:55:46

标签: javascript sharepoint

我需要从我的getItemData函数返回值,如下所示:

function getItemData(success, error) {
    var clientContext = new SP.ClientContext.get_current();
    var ListeEtabScol = clientContext.get_web().get_lists().getByTitle('Etablissements Scolaires');
    var ItemEtabScol = ListeEtabScol.getItemById(123456);

    clientContext.load(ItemEtabScol, 'Title', 'Adresse', 'Commune');
    clientContext.executeQueryAsync(
        function() { success(ItemEtabScol); }, error
    );
}

var test = getItemData(
    function(item){
        return item.get_item('Adresse'); //this is ok, adress is returned
    },
    function(sender, args){
        alert('Erreur : ' + args.get_message());
    }
);

console.log(test); //test is undefined :-( what's wrong ???

但我的测试变量未定义。 知道我的错误吗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

问题已被多次询问和回答......

How to return value from an asynchronous callback function?(简明)

How do I return the response from an asynchronous call?(详细)

简单地说,你需要使用一个回调(一个函数将被"回调"当你要求完成时):

function onComplete(a){ // When the code completes, do this
    console.log(a);
}

function getFive(callback){ 
    var a;
    setTimeout(function(){ //just here to have asynchronicity
         a=5;
         callback(a); 
    },10);
}

并且用法是:

getFive(onComplete);

摘自https://stackoverflow.com/a/6847754/9368855

相关问题