如何使用async和await来避免嵌套回调

时间:2017-05-09 16:22:09

标签: javascript node.js asynchronous async-await

我是nodejs的新手,我尝试使用嵌套回调,但它在大多数情况下使用异步性质使服务器崩溃我如何使用异步更改我的代码并等待崩溃我的服务器。错误是查询未定义。

exports.rpitop = function (req, resp) {
        db.executeSql("SELECT * from Kunden_settings where Benutzer='"+req.body.username+"'", function (data, err) {
            if (err) {
                resp.writeHead(200, { "Content-Type": "text/html" });
                resp.write("<html><head><title>500</title></head></html>");
            }
            else {
                var final_region;
                switch (data[0].product) {
                    case 3:
                        switch (data[0].region) {
                            case 6:final_region  = "nord_h";break;
                            case 7:final_region  = "n_ost_h";break;
                            case 8:final_region  = "ost_h";break;

                        } break;
                    case 4:
                        switch (data[0].region) {
                            case 9:final_region  = "ost_2_d";break;
                            case 10:final_region = "s_ost_d";break;
                            case 11:final_region = "mitte_d";break;

                        } break;
                    case 5:
                        switch (data[0].region) {
                            case 12:final_region = "west_e5";break;
                            case 13:final_region = "r_main_e5";break;
                            case 14:final_region = "s_west_e5";break;

                        } break;
                }

                db.executeSql("SELECT max("+ final_region +") as high, min("+ final_region +") as low from rpi_daten_neu ", function (maxmin, err) {

                    db.executeSql("SELECT * from rpi_daten_neu inner join werte_inc W where datum = (W.bezugsdatum) order by zeit desc limit 1", function (current, err) {
                    if (err) {
                        resp.writeHead(200, { "Content-Type": "text/html" });
                        resp.write("<html><head><title>500</title></head></html>");
                    }
                    else {
                        resp.writeHead(200, { "Content-Type": "x-application/json" });
                        var finalvalue = []
                            for (var i = 0; i < maxmin.length; i++) {
                                for (var i = 0; i < current.length; i++) {
                                    finalvalue.push({
                                        high: maxmin[i].high,
                                        low: maxmin[i].low,
                                        time:momenttime(current[0].zeit, 'HH-mm-ss').format("HH:mm"),
                                        value:current[0][final_region]

                                    })
                                }
                            }

                        resp.write(JSON.stringify(finalvalue));
                    }
                    resp.end();
                });
                });

            }

        });

    }; 

1 个答案:

答案 0 :(得分:0)

要使用async等待,您需要使用标志启动节点应用程序--harmony-async-await:

node --harmony-async-await server.js

node --harmony server.js

接下来,您需要将所有回调函数重写为返回promise的函数。您可以自己完成,但也可以使用https://www.npmjs.com/package/es6-promisify包。

//all functions with await prefix in async function must return promise
const func1 = ()=>{
  return new Promise((resolve, reject)=>{
     ...
  })
};

//all functions with await prefix in async function must return promise
const func2 = ()=>{
  return Promise.resolve(/*your result*/);
}


//async await function example
const asyncFunc = async function(){
    let a = await func1();
    let b = await func2();
    ...
}