Skip to content

Instantly share code, notes, and snippets.

@eynopv
Created September 22, 2022 07:49
Show Gist options
  • Save eynopv/0aadfa774145df8c7e2c7cb606e02d95 to your computer and use it in GitHub Desktop.
Save eynopv/0aadfa774145df8c7e2c7cb606e02d95 to your computer and use it in GitHub Desktop.
Make javascript function which supports promise and callback
// Define function
function wait(timeMS, callback) {
  const f = new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, timeMS);
  });
  
  if (!callback) return f;
  
  f.then(() => callback()).catch((err) => callback(err));
}

// Use with as a promise
wait(500)
  .then(() => console.log('Promise executed'))
  .catch((err) => console.log(err));

// Use with a callback
wait(1000, function (err) {
  if (err) {
    console.log(`Callback errored: ${err.toString()}`);
  } else {
    console.log('Callback executed');
  }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment