異步函數本身應該使用lookup()函數,這是我在異步函數中使用的,但是在回調中返回結果。如何處理javascript中的回調函數?
回調的參數是err和res。 如果lookup()引發了一個錯誤,那麼它應該被傳遞給 err,否則err爲null或undefined。如果lookup()返回了一個結果,那麼它應該被傳遞給res,否則res爲null或者未定義,我有其他兩個測試用於像用戶一樣檢查屬性,但我儘可能地縮短了代碼。問題是在lookupAsync()函數內部回調。
const users = [
{
"login": "norvig",
"firstName": "Peter",
"lastName": "Norvig",
"likes": ["AI", "Search", "NASA", "Mars"]
}
];
// lookupAsync()
const lookupAsync = (login, prop, callback) => {
// Only change code below this line
const found = users.find(function(e) {
return e.login === login;
});
if (!found) {
throw "Could not find user.";
} else {
if (prop in found) {
return found[prop];
} else {
throw "Could not find property";
}
}
//my current concept according to suggestion but trying to set in the
code.
function mycallback(callback) {
var err,res;
callback(err,res);
}
mycallback(function() {
console.log();
});
};
test('lookupAsync() likes', assert => {
const msg = `lookupAsync(<login>, 'likes', callback) should return
likes for the specified user.`;
lookupAsync('norvig', 'likes', function(err, res){
const actual = res;
const expected = ["AI", "Search", "NASA", "Mars"];
assert.deepEqual(actual, expected, msg);
assert.end();
});
});
test('lookupAsync() with unknown user', assert => {
const msg = `lookupAsync() with unknown user should return an error
with the correct message.`;
const value = lookupAsync('nobody', 'likes', function(err, res){
const actual = err.message;
const expected = 'Could not find user.';
assert.equal(actual, expected, msg);
assert.end();
});
});
然後'扔 「一些錯誤」'..什麼問題呢? – webdeb
我的代碼失敗2測試,它必須通過4測試 – damon
哪些測試失敗? – webdeb