2015-06-14 99 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。这篇文章也教会了我如何在生活中取得成功。 –