Javascript promise

It's the same with creating function with callback_function as argument. for example jquery has this function

$.getJSON('/my/url', function(data) {

});

the 2nd argument is a function which will be called when the request is done

in Promise it's the same, but the callback is standardized to only 2 callback: resolve (succeed), reject (failed), both as argument of `then` method.

here's simple example. what i used in my frontend test script / automated bot to wait for certain element to be ready


var tungguSampaiAda = function tungguSampaiAda(selector){
  var janji = new Promise(function(resolve, reject){
    var interval = setInterval(function(){
      var target_node = document.querySelector(selector);
      if (target_node===null) {

      }
      else {
        clearInterval(window.tungguSampaiAdaInterval);
        resolve(target_node);
      }
    }, 500);
  });
  return janji;
};

usage

tungguSampaiAda('#some .thing').then(function(found_node){found_node.innerHTML = 'found!!'; });

with async

async function makin_wait_async(test_function, resolution_in_ms){
  resolution_in_ms = resolution_in_ms || 1000;
  let p = new Promise(function(resolve, reject) {
    
    window.makin_wait_until_timer = setInterval(function(){
      var test_result = test_function();
      if (test_result) {
        clearInterval(window.makin_wait_until_timer);
        resolve(true);
      }
    },resolution_in_ms);
    
  });
  let r = await p;
  return r;
}