2015-06-20 28 views
2

我在使用帆時遇到了多重問題,因爲我無法理解水線承諾及其邏輯。我應該如何處理水線和藍鳥的承諾和回調?

我試過兩個內置藍鳥承諾,甚至還有一個async.waterfall實現,並不能成功。

簡而言之,我正在爲執行數據庫查詢的API編寫代碼,並且通過試圖使用回調函數,它從不響應。

這是我嘗試過純的承諾:

changeFormation: function (request,response) { 

    console.log("changeFormation"); 
    var lineupId = request.params.id; 
    var newFormation = request.param('formation'); 
    var newLineUp = request.param('lineup'); 
    console.log("Receiving" + newFormation); 

    if (["5-4-1", "5-3-2", "4-5-1", "4-4-2", "4-3-3", "3-5-2", "3-4-3"].indexOf(newFormation) === -1) { 
    console.log("No válida"); 
    return response.send(409, "La táctica elegida no es válida"); 
    } 

    LineUp.findOne({id: lineupId}). 
    then(function (foundLineUp) { 

    console.log(foundLineUp); 
    if (!foundLineUp) 
     return response.send(404); 

    if (! foundLineUp.formation) { 

     foundLineUp.formation = newFormation; 

    LineUp.update({id: foundLineUp.id}, foundLineUp).exec(function (err, saved) { 

     if (err) 
     return response.send(500, JSON.stringify(err)); 

     return response.send(202, JSON.stringify(saved)); 
    }); 

    } 

    // If a formation was previously set 
    else if (Array.isArray(newLineUp) && newLineUp.length > 0) { 

     newLineUp.formation = newFormation; 

     LineUp.update({id: newLineUp.id}, newLineUp).exec(function (err,saved) { 
     if (err) 
      return response.send(500,JSON.stringify(err)); 
     return response.stringify(202, JSON.stringify(saved)); 
     }); 
    } 
    console.log("Never reached"); 
    }). 
    catch(function (err) { 
    console.log(err); 
    response.send(500,JSON.stringify(err)); 
    }); 
}, 

在這上面,我可以在控制檯"Never reached"看到。爲什麼!?

而這正是我試圖使用異步模塊:

addPlayer: function (request,response) { 

    // console.log("Add player"); 
    var lineupId = request.params.id; 

    var receivedPlayer = request.param('player'); 
    var playerId = receivedPlayer.id; 
    var bench = receivedPlayer.bench; 
    var place = receivedPlayer.place; 
    var e, r; 

    async.waterfall([ 

    function (cb) { 

     LineUp.findOne().where({id: lineupId}).exec(function (err, foundLineUp) { 
     cb(err,foundLineUp); 
     });}, 

    function (lineup,cb) { 

     Player.findOne().where({id: playerId}).exec(function (err,foundPlayer) { 
     cb(err,lineup, foundPlayer); 
     });}, 

    function (lineup, player, cb) { 
     if (!player) { 
     console.log("Jugador no existe"); 
     cb(null, {status: 409, msg: "El jugador " + playerId + " no existe"}); 
     } 

     if (!lineup.formation) { 
     console.log("No hay táctica") 
     cb(null, {status: 409, msg: "No se ha elegido una táctica para esta alineación"}); 
     } 

     if (lineup.squadIsComplete()) { 
     console.log("Ya hay 15"); 
     cb(null, {status: 409, msg: "La plantilla ya contiene el máximo de 15 jugadores"}); 
     } 

     if (lineup.playerWasAdded(player.id)) { 
     console.log("Jugador ya en alineación") 
     cb(null, {status: 409, msg: "El jugador ya ha sido agregado a la alineación"}); 
     } 

     if (lineup.fieldIsComplete() && !bench) { 
     console.log("Ya hay 11 en el campo"); 
     cb(null, {status: 409, msg: "Ya se han agregado los 11 jugadores de campo"}); 
     } 

     player.bench = bench; 
     player.place = place; 

     lineup.players.push(player); 

     console.log("MaxForeign " + lineup.reachesMaxForeignPlayers()); 
     console.log("BudgetLimit " + lineup.reachesBudgetLimit()); 
     console.log("SameTeam " + lineup.reachesMaxSameTeamLimit()); 
     console.log("reachesMaxSameFavoriteTeamLimit " + lineup.reachesMaxSameFavoriteTeamLimit()); 


     // If any of rule restrictions evaluates to true ... 
     // Using lodash _.some with out second argument which defaults to _.identity 
/*  if (_.some([ lineup.reachesMaxForeignPlayers(), 
        lineup.reachesBudgetLimit(), 
        lineup.reachesMaxSameTeamLimit(), 
        lineup.reachesMaxSameFavoriteTeamLimit()])) { 

     return response.send(409, "La inclusión de este jugador no satisface las reglas del juego"); 
     }*/ 

     LineUp.update({id: playerId}, lineup).exec(function (err, saved) { 
     cb(err, {status: 202, msg: JSON.stringify(saved)}); 
     }); 
    } 
    ], 

    function (err, result) { 
    console.log("About to respond"); 
    if (err) 
     respond.send(500); 
    else 
     response.send(result.status, result.msg); 
    }); 

    console.log("Never reached"); 
}, 

這給不超時,但它並不奇怪,當它應該更新文檔。它的日誌記錄"never reached"然後"about to respond"但這是正常的,我猜。

到目前爲止,我該如何處理這一切?

+1

爲什麼你會期待'console.log(「永遠不會到達」);'永遠不會到達?沒有達到的唯一情況就是發送404。 – Bergi

+2

嗯,這兩個代碼片段似乎完全不相關,並使用不同的方法。請只詢問每個問題的單個問題(儘管您可能包含多種不同的方法來解決問題) – Bergi

回答

2

在上面我可以看到在控制檯「從未到達」。爲什麼!?

因爲您將異步代碼與sync'd代碼混合在一起。如果你這樣做:

function(){ 
    console.log('init'); 
    someAsyncMethod(function callback(){ 
    return console.log('async done'); 
    }); 
    console.log('Never reached'); 
} 

您將獲得:

init 
Never reached 
async done 

由於異步代碼會被執行之後。我建議你閱讀thisthis以更好地理解異步回調。

這不是超時,但奇怪的是它不應該更新文檔。

很難說這是怎麼回事,因爲我們不知道的LineUp模型定義,我們不前和update電話後知道lineup內容。你確定LineUp.update()跑了嗎?爲什麼不在回調中添加console.log()以查看結果?

到目前爲止,我該如何處理這一切?

在我看來,你已經接近實現你的目標。如果您分享LineUp的模型定義和更多日誌記錄,我們將能夠爲您提供更多幫助。

+0

嘿,感謝您的回覆,我確實在我的代碼甚至是這篇文章中做出了愚蠢的假設。不過,我發現這個問題,導致我完全混淆。我已經發布了一個單獨的問題,如果你有Sails的經驗,我希望你能檢查出來:http://stackoverflow.com/questions/30958122 – diegoaguilar