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