2015-06-14 52 views
3

天兒真好所有,如何使多個MySQL查詢在節點與承諾

我試圖轉移到節點將一些舊的PHP代碼,以及旅程的一部分一直在試圖找出最好的方法對我的數據庫執行sql查詢(我正在使用SQL,因此我可以移植現有的數據庫)。

我有他們的工作,但遇到了「末日金字塔」的問題,它是隨後的範圍問題(即返回的值不baing可用於後續「然後」)。

排序的代碼的一個例子,我這​​裏是:(dbPool.queryOPromise返回封裝在承諾的查詢)

dbPool.queryOPromise(query)                      
.then(function(result){                       
    console.log(result);                       
    var query = {                         
     sql:"INSERT INTO newusers (newuserid, ipaddress, email) VALUES (?,?,?)",          
     values: [newuserid, ipAddress, email]                  
    };                            
    dbPool.queryOPromise(query)                     
    .then(function(value){                       
     console.log(value);                       
     if(value.code==200) {                      
      res.status(200).json({code:200, status:"New User Created"});            
     } else {                          
      res.status(400).json({code:value.code, status:"Error creating new user: ".value.status}); 
     }                           
    })  
}) 

沒有人有攻擊這種情況下,最好的方式有何看法?

謝謝!

+0

實際問題是什麼? – thefourtheye

回答

5

你應該回報隨後的承諾,而不是要求他們

dbPool.queryOPromise(query) 
.then(function(result) { 
    console.log(result); 
    var query = { 
     sql: "INSERT INTO newusers (newuserid, ipaddress, email) VALUES (?,?,?)", 
     values: [newuserid, ipAddress, email] 
    }; 
    // RETURN the second promise, 
    return dbPool.queryOPromise(query); 
}) 
.then(function(value) { 
    console.log(value); 
    if (value.code == 200) { 
     res.status(200).json({code: 200, status: "New User Created"}); 
    } else { 
     res.status(400).json({code: value.code, status: "Error creating new user: ".value.status }); 
    } 
}) 
.catch(console.error); // and always catch the errors at the end. 

它在使用的承諾#1新手的錯誤.then的。 Checkout this wonderfully written article addressing issues exactly like this

+0

謝謝滯後,這是超級有用的,可能是迄今爲止我見過的最佳承諾。乾杯! –

+3

這篇文章教會了我需要知道的成就人生的一切。比知道如何釣魚更好。 –

+0

也有這個SAME確切的問題,'返回後續諾是關鍵,謝謝laggedreflex。這篇文章也教會了我如何在生活中取得成功。 –