2017-07-14 34 views
-5

異步函數本身應該使用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(); 
}); 
}); 
+1

然後'扔 「一些錯誤」'..什麼問題呢? – webdeb

+0

我的代碼失敗2測試,它必須通過4測試 – damon

+1

哪些測試失敗? – webdeb

回答

0

讓我爲你做

const lookupAsync = (login, prop, callback) => { 
    const found = users.find(function(e) { 
    return e.login === login; 
    }); 

    if (!found) { 
     callback(new Error("Could not find user.")); 
    } else { 
     if (prop in found) { 
     callback(null, found[prop]); 
     } else { 
     callback(new Error("Could not find property")); 
     } 
    } 
    } 
+0

非常感謝,只有第二次測試失敗:(,我很抱歉再次打擾你 – damon

+0

再次檢查,請檢查錯誤的字符串 – webdeb

+0

一切工作正常,我必須說你是一個非常有才華的程序員,我的夢想是成爲某人像你們在堆棧溢出幫助,我想感謝你1000次。 – damon