使用async / await在hapi.js的处理函数中返回数据

时间:2018-10-26 16:47:50

标签: node.js typescript async-await hapijs

我想从处理函数中返回dataSet。但是,它嵌套在我的诺言链中。我正在尝试使用await/async,但数据的值仍未定义。关于如何执行此操作的想法?

handler: (request, h) => {

    let data: any;
    connection.connect((err) => {
        if (err) {
            console.error("Error-------> " + err);
        }
        console.log("Connected as id " + connection.threadId);
        connector.getAllEvents()
            .then(async dataSet => {
                console.log(dataSet);
                data = await dataSet;
            });
    });
    return data;
}

Err不会被抛出,因为登录到控制台会打印出我正在寻找的值。

2 个答案:

答案 0 :(得分:2)

为此,您需要使handler返回Promise,并在处理程序中,将connection.connect块包装为Promise

例如

handler: (request, h) => {
    // wrap connector.connect(...) in a Promise
    return Promise<any>((resolve, reject) => {
        connection.connect(err => {
           if (err) {
               console.error("Error -----> ", err);

               // error in connection, propagate error via reject
               // and do not continue processing
               return reject(err);
           }

           console.log("Connected as id " + connection.threadId);
           connector.getAllEvents()
               // don't think you need this to be async
               // as connector.getAllEvents() will should return a Promise<T>
               // and .then() is like a .map() so its first argument is a T
               // rather than a Promise<T> 
               .then(dataSet => {
                   console.log(dataSet);

                   // we finally have our value
                   // so we propagate it via resolve()
                   resolve(dataSet);
               });
        });
    });
}

答案 1 :(得分:1)

返回数据时未对其进行初始化。您可以通过在返回之前添加另一个日志语句来对其进行测试,您会看到它在Compiled successfully! You can now view testapp in the browser. Local: http://localhost:3000/ On Your Network: http://192.168.1.123:3000/ Note that the development build is not optimized. To create a production build, use npm run build.

之前打印

我不知道console.log(dataSet);返回什么(它是什么框架?),但是您可以证明它的正确性。然后,您要么返回一个承诺以“连接并获取数据”,然后让调用者等待它,要么您在函数内部connection.connect上对其进行承诺,并在实现承诺之后返回数据。