Skip to content

Instantly share code, notes, and snippets.

@jofftiquez
Last active February 27, 2024 02:23
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jofftiquez/c647654e76271119ea714805cfdb5ca2 to your computer and use it in GitHub Desktop.
Save jofftiquez/c647654e76271119ea714805cfdb5ca2 to your computer and use it in GitHub Desktop.
Mock HTTP request in javascript using promise and timeout.
const mock = (success, timeout = 1000) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if(success) {
resolve();
} else {
reject({message: 'Error'});
}
}, timeout);
});
}
const someEvent = async () => {
try {
await mock(true, 1000);
} catch (e) {
console.log(e.message);
}
}
@yairEO
Copy link

yairEO commented Nov 13, 2019

Suggestion: There should be some kind of optional memory to allow clearing the timeout (aka "abort") when the same request leaves again

@yairEO
Copy link

yairEO commented Nov 13, 2019

Also, add a default timeout:

}, timeout || 1000)

@jofftiquez
Copy link
Author

Thanks @yairEO

@The-Anomaly
Copy link

Thanks for this!

@corners2wall
Copy link

Cool, thanks a lot

@xgqfrms
Copy link

xgqfrms commented Sep 8, 2023

another version

const getMockData = async (options = {
  data: '',
  error: 'unknown server error',
  delay: null
}) => {
  const {data, error, delay} = options;
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if(!!data) {
        resolve({
          type: 'Success ✅',
          data,
        });
      } else {
        reject({
          type: 'Error ❌',
          message: error,
        });
      }
    }, delay || 1000);
  });
}

// test cases
(async () => {
  try {
    const success = await getMockData({data: [1,2,3]});
    console.log(success.data);
  } catch (err) {
    console.log(err.message);
  }
  try {
    const error = await getMockData({error: '404 not found error', delay: 3000});
    console.log(error);
  } catch (err) {
    console.log(err.message);
  }
})();

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