4

I would like to make a function to pass a list name, if it exists, then append random number to its name and create a new one, if there's no list with the passed list name, then create it.

So I am doing like the code below:

var listName;
function _addList(listName){
var promise= _checkIfExists(listName);
    promise.done(function(){
    //Add the list to the collection
    });
    }//end function


function _checkIfExists(listName){
var mypromise = _getListByName(listName);
var dfd = $.Deferred();

mypromise.then(
    function(data, status, jqXHR){
       listName= generateName(); //list exists, then generate another name
     },
     function(jqXHR, status, error){
       listName= listName; //object doesn't exist, use same name
     });

return dfd.promise();    
};

    function _getListByName(listName){
    var url = "site url..../web/lists/getByTitle.."
return ($.ajax({..}).promise();
    }

But once am trying to get a list that doesn't exist, I am having a 404 error and it stops. Shouldn't the code just calls the fail part of the promise and continue with the execution after return dfd.promise() ?

3
  • No, its a promise, so return dfd.promise() has already executed. Add loads of console.log so you see the order Commented Dec 23, 2015 at 7:57
  • thanks Danny I am returning the promise from checkifexist function, and checking this promise when it's done in the addlist function. what's wrong with that can you elaborate? Commented Dec 23, 2015 at 9:44
  • Add log statements all over the place and see what happens. I am no compiler, but what I read here you always end up in promise.done. Because you split it in seperate functions you make it difficult to read. Do it all in one function with promise chains first. If that works split it into seperate functions (but only when you want to reuse code) Commented Dec 23, 2015 at 10:07

1 Answer 1

4

Continued from comments

Here is code with both Callback functions (left in as an example) and Methods chained to the $.ajax promise

    console.clear();
    var site=_spPageContextInfo.webAbsoluteUrl;
    var listName='Documnten';
    $.ajax({
        url: site + "/_api/web/lists/getbytitle('" + listName + "')",
        method: "GET",
        contentType: "application/json;odata=verbose",
        async: true,
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success:function(data){//this is a Callback function
            console.log('success Callback', data)
        },
        error:function(data){//this is a Callback function
            console.log('error Callback', data)
        }
    }).done(function(data){//this is a method
        console.log('success ',data);
        listName=String.format( "{0}{1:yMdhms}" , listName , new Date() );
    }).fail(function(data){//this is a method
        console.error('error ',data);
    }).always(function(data){//this is a method
        console.log('always ',data);
        console.info('Create List:',listName);
    });

So the .done method is interchangable with the success Callback

Note that they are both executed in this example.. Callbacks first.

(modern) Promises are more powerful, (oldschool) Callbacks are used in most blogposts.

I had to RTFM as well

.success and .error methods are deprecated since jQuery 1.8 (use .done and .fail) but do still work (so you will see them in blogposts)

Update 1 - a no jQuery solution

just for fun (and without promises)

var site=_spPageContextInfo.webAbsoluteUrl,
    listName='Documenten',
    xhr = new XMLHttpRequest(); 
xhr.open("GET",site+"/_api/web/lists/getbytitle('"+listName+"')", true);
xhr.setRequestHeader("Accept","application/json;odata=nometadata");
xhr.setRequestHeader("X-RequestDigest",document.getElementById('__REQUESTDIGEST').value);
xhr.onreadystatechange = function () {
  if (xhr.readyState != 4) return;//no response received yet 
  if (xhr.status===200) listName=String.format("{0}{1:yMdhms}",listName,new Date() );
  console.info('Create List:',listName);
};
xhr.send();

J1 J5 iREST iJS iXHR

3
  • 1
    When do I use .success vs. .done, and .fail vs. .error, I am confused about it. Commented Dec 23, 2015 at 11:10
  • 1
    Like you learn any language.. learn what the words mean then apply them. The other way around gets you RTFM answers eventually Commented Dec 23, 2015 at 11:26
  • updated post makes much more sense with .fail and .done Commented Dec 23, 2015 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.