回调函数似乎在父函数完成之前触发

时间:2018-08-16 20:37:50

标签: javascript callback

我一直在自学JS,无法使该脚本正常工作。如果重要的话,它位于SharePoint网站上。根据我在这里学到的知识:https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced 在这里:How to use a return value in another function in Javascript?,似乎应该。我想在getUserInfo()完全完成后触发updateListItem()。

function getUserInfo(callbackUI, par1, par2, par3, par4, par5, par6) {
    var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;
    var users = peoplePicker.GetAllUserInfo();
    var context = new SP.ClientContext.get_current();
    this.user = context.get_web().ensureUser(users[0].Key);
    context.load(this.user);
    context.executeQueryAsync(
         Function.createDelegate(null, ensureUserSuccess), 
         Function.createDelegate(null, onFail)
    );
    callbackUI(par1, par2, par3, par4, par5, par6);  
}

function ensureUserSuccess() {
    var testone = (this.user.get_id());
    $('#userId').html(this.user.get_id());
    console.log(testone);
    return this.user.get_id();
}

function onFail(sender, args) {
    alert('Query failed. Error: ' + args.get_message());
}

下面的click事件可以工作,但是即使我的HTML格式中的值正确,也无法识别“ usersID”的值(在sureUserSuccess()中设置)。

$("body").on("click",".savePartner",function(){
    var thisID  = $(this).closest(".singleItemWrap").find(".bigID").text();
    var usersID = $(this).closest(".singleItemWrap").find("#userId").val();

    var itemProperties = {'ITContactId': usersID};
    getUserInfo(updateListItem,_spPageContextInfo.webAbsoluteUrl,'GFSTechIntake',thisID,itemProperties,printInfo,logError);


    //updateListItem(_spPageContextInfo.webAbsoluteUrl,'GFSTechIntake',thisID,itemProperties,printInfo,logError);
    function printInfo()
    {
        console.log('PARTNER UPDATED!');
      //  alert("This item has been assigned!");
    }
    function logError(error){
        alert("An error occurred. Please refresh and try again.");
        console.log(JSON.stringify(error));
    }

}); 

我花了数小时尝试在网上找到的其他内容,但似乎无法做到这一点。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您不能在另一个函数旁边使用异步函数,并且期望第一个函数等待另一个函数,在这种情况下为executeQueryAsync()callbackUI(),将要执行的函数放在回调的最后第一个:

function getUserInfo(callbackUI, par1, par2, par3, par4, par5, par6) {
    var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;
    var users = peoplePicker.GetAllUserInfo();
    var context = new SP.ClientContext.get_current();
    this.user = context.get_web().ensureUser(users[0].Key);
    context.load(this.user);
    context.executeQueryAsync(
         () => {
             Function.createDelegate(null, ensureUserSuccess);
             callbackUI(par1, par2, par3, par4, par5, par6);
         }, 
         Function.createDelegate(null, onFail)
    );

}