jQuery.getJSON

by Artem

JavaScript

/* Replicate behavior of $.getJSON function, then callback should always have this as Response object
$.getJSON('https://dog.ceo/api/breeds/image/random')
  .then(function() {
    console.log('this ', this); // response info
});
*/

function CustomPromise(promiseFn) {
  this.nativePromise = new Promise(promiseFn);
  this.context = {};
}

CustomPromise.prototype = Object.create(Promise.prototype);
CustomPromise.prototype.constructor = CustomPromise;

CustomPromise.prototype.then = function(fn) {
  this.nativePromise = this.nativePromise.then((v) => {
    return fn.bind(this.context)(v);
  });
  return this;
};

/* var p = new CustomPromise(function(resolve) {
  resolve(12);
});
p.then(function(v) {
  console.log('this ', this);
  return 100;
})
.then(function(v) {
  console.log('this ', this);
  console.log('value ', v);
}); */

function getJSON(url) {
  const fetchPromise = fetch(url).then(async function(response) {
    const data = await response.json();
    return data;
  });

var promise = new CustomPromise((resolve) => {
  console.log(111, this)
  return fetchPromise.then(function(data) {
    console.log('data ', data, this);
    resolve(data);
  });
});

promise.context = {};

return promise;
}

getJSON('https://dog.ceo/api/breeds/image/random').then(function(data) {
  console.log(this); // response info?
});