So,i have a task,to make a function 'mocker' which will return defined data with 1 second delay.The problem is that i'm new in JavaScript world and idk how to do this.I tried to take this way:
mocker = function mocker(data) {
var delayInMilliseconds = 1000;
setTimeout(function () {
return data;
}, delayInMilliseconds);};
But it doesnt satisfy the assignment. I have this example :
const getUsers = mocker([{id: 1, name: 'User1'}]);
getUsers().then((users) => { // Will fire after 1 second.
console.log(users); // result: [{id: 1, name: 'User1'}];
});
And this is function description for test :
describe('mocker', () => {
describe('users mocker', () => {
const usersData = [{id: 1, login: 'mickey'}, {id: 2, login: 'billy77'}, {id: 3, login: 'coooool123'}];
let getUsers;
beforeEach(() => {
getUsers = mocker(usersData);
});
it('should return users data', async () => {
const resultData = await getUsers();
assert.deepStrictEqual(resultData, usersData);
});
it('should return users data in asynchronous way', () => {
const resultData = getUsers();
assert.notDeepStrictEqual(resultData, usersData);
});
});
});
@param data: {Array | Object}
@returns {Function}
Can you guys please help me? Thanks in advance.
CodePudding user response:
The test suggests it's a little more complicated than just creating a function that returns some data after a second.
This line:
getUsers = mocker(usersData);
is saying that mocker
needs to 1) accept some data and 2) return a function that we assign to getUsers
. When we call getUsers
it will then call that function to return the promise of data.
So when we get here:
const resultData = await getUsers();
we're calling that function we assigned to getUsers
that promises to return some data (or not) after a second.
const usersData = [{id: 1, login: 'mickey'}, {id: 2, login: 'billy77'}, {id: 3, login: 'coooool123'}];
// `mocker` accepts some data and returns a
// function. This function is assigned to `getData`, and
// when `getData` is called this is the function that gets executed.
// It returns a promise that after one second data will be returned.
function mocker(usersData) {
return function () {
return new Promise((res, rej) => {
setTimeout(() => res(usersData), 1000);
});
}
}
// So we call `mocker` and assign the function it
// returns to `getUsers`
const getUsers = mocker(usersData);
async function main() {
// We can then call `getUsers` to get the data
// after one second has passed
console.log(await getUsers());
}
main();
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Additional documentation