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

标签 node.js typescript async-await hapi.js

我想从我的处理函数返回dataSet。然而它嵌套在我的 promise 链中。我正在尝试使用 await/async 但数据的值仍然未定义。想知道如何做到这一点吗?

处理程序:(请求,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;
}

由于登录到控制台会打印出我正在查找的值,因此不会抛出错误。

最佳答案

为了做到这一点,您需要使 handler 返回一个 Promise,并在处理程序中包装 connection.connect block 带有 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);
               });
        });
    });
}

关于node.js - 在 hapi.js 的处理函数中使用 async/await 返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53013168/

相关文章:

node.js - NodeJS 流不等待异步

java - 从 Android 向 Node.js 服务器发送图像会以 URL 样式进行编码,无法很好地解码

javascript - 使标记弹出

c# - FakeItEasy - 是否可以异步测试约束(即 MatchesAsync)?

javascript - 如何修复 Handlebars 中的前端 javascript 从服务器捕获未定义的值?

javascript - 在 CoffeeScript 模块中导出对象的优雅方法是什么?

javascript - 无需等待响应即可调用云函数

javascript - 在 Angular 2 组件内的 javascript 中访问 Typescript 变量值

javascript - Box Node SDK 未使用 readStream 拉取文件

c# - await 在这个函数中做了什么?