-1

My script:

var testApp = (function($){
    var data = [{
        "layout": "getSample",
         "view": "conversations",
         "format": "json",
    }];

    var Data = 'default';
    function ajaxCall(opt) {
        return new Promise(function(resolve, reject) {

            jQuery.ajax({

               method: "POST",
               url: localStorage.getItem("root")+"/index.php",
               "data": opt,
               error: function() {
                   alert('error');
               },  
               success: function(result) {
                   console.debug(result);
                   resolve(result);

               }//end success
          });//end ajax

       });//end promise
    }
    return {

        render: function(opt) {
            if(typeof opt === 'object') {
                var list = {
                    data : [opt]
                }

                //here I'm passing list object's data to be used in ajaxCall function.That's the reeason I used call method. It's data is passed from another page.
                ajaxCall.call (list, list.data).then(function(v) { 
                    console.log("v "+v); // nothing happens yet...expecting for the success object to be passed here
                }).catch(function(v) {
                    //nothing to do yet
                });


            }
        }

    };//end return
})(jQuery);

Is the correct way of using promise with ajax?

ajaxCall.call (list, list.data).then(function(v) { 
 console.log("v "+v); // doesn't return anything
}).catch(function(v) {
//nothing to do yet
});

referred: How do I return the response from an asynchronous call?

Community
  • 1
  • 1
112233
  • 2,406
  • 3
  • 38
  • 88
  • 1
    `jQuery.ajax()` *already* returns a promise. Apart from that it's unclear what your code is supposed to achieve. Please start with indenting it properly and add an explanation about its purpose, what you expect to happen, and what happens instead. Also remove unused code like that commented-out for loop. Either you need a line of code, or you don't - make up your mind. – Tomalak Jul 25 '16 at 14:47
  • @Tomalak, I made up my mind and edited the code. See if you can answer – 112233 Jul 25 '16 at 15:11

2 Answers2

0

well, its a simple fix I found.. //below line of code, moved above return new promise and it worked

var opt = jQuery.extend({}, data[0], opt[0]);

112233
  • 2,406
  • 3
  • 38
  • 88
  • 1
    Too bad that this line no longer exists in the code of your question. Also, you should think about the first sentence in my comment above again: `jQuery.ajax()` *already* returns a promise. – Tomalak Jul 25 '16 at 15:34
0

jQuery Ajax functions already return promises. You don't have to turn them into promises manually.

var testApp = (function($) {
    var ajaxDefaults = {
        "layout": "getSample",
        "view": "conversations",
        "format": "json",
    };

    // this can be re-used in all your Ajax calls
    function handleAjaxError(jqXhr, status, error) {
        console.error('Ajax error', error);
    });

    function ajaxCall(opt) {
        var url = localStorage.getItem("root") + "/index.php",
            data = jQuery.extend({}, ajaxDefaults, opt);

        return $.post(url, data).fail(handleAjaxError);
    }

    return {
        render: function(opt) {
            return ajaxCall(opt).then(function (result) {
                console.log("v " + result);
                return result;
            });
        }
    };
})(jQuery);
  • You don't need to use .call() to call a function. It doesn't make a lot of sense in this case, either. If it is not an object method, but a stand-alone function, call it normally and pass arguments.
  • There is no guarantee that localStorage.getItem("root") contains any value, but your code ignores this possibility. That's a bug.
  • You don't want two variables data and Data in your code. Don't set up trip wires like this.
  • There is no need to use $.ajax() when $.post()/$.get() can do the job in one line.
  • Return something from your render() method and from its .then() handler, too, so you can chain more code elsewhere in your application, e.g.

    app.render({data: 1234}).then(function (result) {
        // ...
    });
    
Tomalak
  • 332,285
  • 67
  • 532
  • 628