Last active
February 27, 2024 02:23
-
-
Save jofftiquez/c647654e76271119ea714805cfdb5ca2 to your computer and use it in GitHub Desktop.
Mock HTTP request in javascript using promise and timeout.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Also, add a default timeout
:
}, timeout || 1000)
Thanks @yairEO
Thanks for this!
Cool, thanks a lot
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
Suggestion: There should be some kind of optional memory to allow clearing the timeout (aka "abort") when the same request leaves again