我想从我的处理函数返回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/