所以,我有一個任務,要創建一個函式“ mocker ”,它會以 1 秒的延遲回傳定義的資料。問題是我是 JavaScript 世界的新手,不知道如何做到這一點。我試圖采取這種方式:
mocker = function mocker(data) {
var delayInMilliseconds = 1000;
setTimeout(function () {
return data;
}, delayInMilliseconds);};
但它不滿足分配。我有這個例子:
const getUsers = mocker([{id: 1, name: 'User1'}]);
getUsers().then((users) => { // Will fire after 1 second.
console.log(users); // result: [{id: 1, name: 'User1'}];
});
這是 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}
你們能幫幫我嗎?提前致謝。
uj5u.com熱心網友回復:
測驗表明,這比創建一個在一秒鐘后回傳一些資料的函式要復雜一些。
這一行:
getUsers = mocker(usersData);
是說mocker需要 1) 接受一些資料和 2) 回傳一個我們分配給的函式getUsers。當我們呼叫getUsers它時,它將呼叫該函式以回傳資料的承諾。
所以當我們到達這里時:
const resultData = await getUsers();
我們正在呼叫我們分配給它的函式,getUsers它承諾在一秒鐘后回傳一些資料(或不回傳)。
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();
附加檔案
承諾
async/await
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/351015.html
標籤:javascript 异步 任务
下一篇:JS如何使var長度限制
