0

I am using jquery version 3.5.1 which supports then and catch for ajax requests.

What is recommended practice between below two codes?

First wraps ajax call in Promise, and second returns ajax call directly.

First

function first() {  
    return new Promise(function(resolve, reject) {
    $.ajax({
            url: '...',
            method: 'get',          
            success: function(response){
                resolve(response.title + ' first');
            },
            error: function(error){
                reject();
            }
        });
  });
}

first().then(function(data){
    console.log(data);
  });

OR

Second

function second() {  
    return $.ajax({
              url: 'https://jsonplaceholder.typicode.com/todos/1',
                method: 'get'            
              })
                .then(function(response){           
                  return response.title + ' second';
                })
  }

second().then(function(data){
    console.log(data);
  });

I somewhere read that wrapping ajax call inside Promise is anti-pattern. Which code should I use?

I created js fiddle for this example

AjinkyaBhagwat
  • 683
  • 2
  • 6
  • 18
  • `$.ajax` should return a Promise - or close enough - depends on jQuery version - you could even `return Promise.resolve($.ajax(....))` that way you get a native Promise (not that that should matter, a thenable is a thenable) – Jaromanda X Nov 05 '20 at 08:30
  • thank you !. so that means return $.ajax() is recommended and wrapping $.ajax inside new Promise is anti-pattern. – AjinkyaBhagwat Nov 05 '20 at 08:54
  • 1
    exactly - unless the jquery version is very old, then I'd recommend the "anti-pattern" - but nobody should be using jquery that is that old – Jaromanda X Nov 05 '20 at 09:27

0 Answers0