如何使用promises在Node中进行多个mysql查询

And*_*son 3 mysql node.js promise

G'day所有,

我正在尝试将一些旧的PHP代码转换为Node,并且部分旅程一直在试图找出对我的数据库执行sql查询的最佳方法(我正在使用SQL,因此我可以移植现有的数据库) .

我让他们工作,但遇到了"末日金字塔"问题,并且随后的范围问题(即返回的值不能随后用于"当时").

我在这里的代码类型的一个示例是:(dbPool.queryOPromise返回包含在promise中的查询)

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});
        }                                                                                                           
    })       
})
Run Code Online (Sandbox Code Playgroud)

有没有人对攻击这种情况的最佳方法有看法?

谢谢!

lag*_*lex 5

你应该返回后续的承诺,而不是回复.then它们

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. 
Run Code Online (Sandbox Code Playgroud)

这是使用承诺的第1个新手错误.查看这篇精彩的文章,解决与此类似的问题

  • 这篇文章教会了我在生活中取得成功所需要知道的一切.比知道如何钓鱼更好. (4认同)