2016-08-01 68 views
0

這個NodeJS代碼有什麼問題?nodejs帶回路的異步控制流程

我有以下的NodeJS snipt。

Profile.findOne(profileId, cb) //is sync function 


function getProfiles(users, cb) { 
    var results = []; 
    var n = users.length; 
    users.forEach(function(user, i) { 
    Profile.findOne(user.profileId, function(err, prf) { 
     if (err) { 
     return cb(err, null); 
     } 
     console.log(prf); 
     console.log(user.profileId); 
     results.push(prf); 
     if (i + 1 == n) { 
     console.log('looping done'); 
     return cb(null, results); 
     } 
    }); 
    }); 
} 

// some where 
var userslist = [{ 
    name: 'ab', 
    profileId: 'daf242' 
}, { 
    name: 'cd', 
    profileId: 'hg535h' 
}, { 
    name: 'ef', 
    profileId: 'cvxv445' 
}]; 
getProfiles(userslist, function(err, data) { 
    if (err) { 
    //do this 
    } else { 
    //do that 
    } 
}); 

問題是結果對所述第一簡檔的型材陣列。 像

[ 
     {username:'ab',avatarUrl:'abcd.png'} 
     {username:'ab',avatarUrl:'abcd.png'}, 
     {username:'ab',avatarUrl:'abcd.png'} 
    ] 

但我期待的數組profiles不同。

我錯過了什麼?

+0

試試這個:https://jsfiddle.net/rayon_1990/Ldd0mcrj/ – Rayon

回答

1

這裏混合了同步和異步代碼。您的forEach循環正在同步運行,但Profile.findOne方法是異步的。然後它調用傳遞給初始函數的回調函數。你應該看看使用async for an asynchronous for loop

但是,在你的問題中有很多事情表明你還沒有完全掌握Node.js的異步特性。嘗試閱讀該主題,例如callback hell

+0

你能否解釋一下_ 「調用傳遞到初始功能的回調」 _? – Rayon

+0

@MrWillihog你能否提出解決問題的方法,我會閱讀鏈接並減輕話題。但現在我需要qucik suggetion/fix。 – Zstudent

+0

@Rayon - 'getProfiles'函數傳遞一個回調('cb')。這在'Profile.findOne'方法中被調用。因此,實際上,要找到的第一個配置文件將其結果傳遞給'getProfiles'函數的回調。 – MrWillihog

0

使用async或承諾

var async = require('async'); 
... 
async.map(users, Profile.findOne, function(err, results) { 
    if (err) 
     return ...// process errors; 

    userlist = results; 
})