Skip to content

Instantly share code, notes, and snippets.

@h3xxx
Forked from treyhuffine/poll.js
Created July 3, 2020 11:33
Show Gist options
  • Save h3xxx/bbeb72a6036a4505a4107f9f2c40f434 to your computer and use it in GitHub Desktop.
Save h3xxx/bbeb72a6036a4505a4107f9f2c40f434 to your computer and use it in GitHub Desktop.
const poll = async ({ fn, validate, interval, maxAttempts }) => {
let attempts = 0;
const executePoll = async (resolve, reject) => {
const result = await fn();
attempts++;
if (validate(result)) {
return resolve(result);
} else if (maxAttempts && attempts === maxAttempts) {
return reject(new Error('Exceeded max attempts'));
} else {
setTimeout(executePoll, interval, resolve, reject);
}
};
return new Promise(executePoll);
};
@h3xxx
Copy link
Author

h3xxx commented Jul 6, 2020

  let attempts = 0;

  const executePoll = async (resolve, reject) => {
    const result = await fn();
    attempts++;

    if (validate(result)) {
      return resolve(result);
    } else if (maxAttempts && attempts === maxAttempts) {
      return reject(new Error("Exceeded max attempts"));
    } else {
      setTimeout(executePoll, interval, resolve, reject);
    }
  };

  return new Promise(executePoll);
};

function ___f() {
  var promise = new Promise(function(resolve, reject) {
    window.setTimeout(function() {
      resolve({cc: 'PL'});
    }, 2000);
  });
  return promise;
}

poll({
  fn: ___f,
  validate: (result) => {
    console.log(result);
    const isOk = result.cc === 'PL'
    if (isOk) {
      console.log('validated');
    }
    return isOk;
  },
  interval: 2000,
  maxAttempts: 3
}).then(function () {
  console.log('resolved');
}).catch(function () {
  console.log('rejected');
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment