Javascript 如何使用final通过承诺链传递变量
我正在尝试为Javascript 如何使用final通过承诺链传递变量,javascript,node.js,express,promise,Javascript,Node.js,Express,Promise,我正在尝试为expressapi构建日志,但是在获取要注销的数据时遇到问题 我可以在finally块中记录原始req和res对象,但不确定如何访问SQL响应 const sql = require("mssql") const config = require("../config") router.get("/express-route", (req, res) => { sql.connect(config.properties).then(pool => { re
expressapi
构建日志,但是在获取要注销的数据时遇到问题
我可以在finally
块中记录原始req
和res
对象,但不确定如何访问SQL响应
const sql = require("mssql")
const config = require("../config")
router.get("/express-route", (req, res) => {
sql.connect(config.properties).then(pool => {
return pool.request()
.input('username', sql.NVarChar(32), req.params.username)
.execute('do_something_with_username')
.then(response => res.send(response) // pass this response
.catch(err => res.send(err))
.finally(() => {
console.log('response', response) // to here
sql.close()
})
})
}
如何从第一个然后块获取响应,并将其传递到最后的块,以便在另一个函数中使用
finally回调不会收到任何参数,因为没有可靠的方法来确定承诺是履行了还是拒绝了。这个用例正好适用于您不关心拒绝原因或履行价值的情况,因此不需要提供它。()
相反,只需使用。然后
:
const sql = require("mssql")
const config = require("../config")
router.get("/express-route", (req, res) => {
sql.connect(config.properties).then(pool => {
return pool.request()
.input('username', sql.NVarChar(32), req.params.username)
.execute('do_something_with_username')
.then(response => {res.send(response); return response;}) // pass this response
.catch(err => res.send(err))
.then(response => {
console.log('response', response) // to here
sql.close()
})
})
}
实际上,您可以通过在异步函数中编写代码来简化事情
const sql = require("mssql")
const config = require("../config")
router.get("/express-route", (req, res) => {
sql.connect(config.properties).then(async pool => {
try {
const response = await pool.request()
.input('username', sql.NVarChar(32), req.params.username)
.execute('do_something_with_username');
// do another request
const otherResponse = await pool.request() ... ;
res.send(response);
} catch (err) {
res.send(err);
} finally {
sql.close();
}
})
}
这可以让您以更线性的方式编写代码。我们的想法是用另一个pool.request…
来替换“console.log('response',response)`来写回SQL…您可以这样做,只需像我对第一个pool.request那样打电话。我的回答中的request谢谢您的反馈!!:)令人惊叹的。非常感谢。不要忘记,如果出现错误,response
将是undefined
,因为这是catch
处理程序返回的结果。你不能-如果请求
或输入
或执行
中有错误,最后会运行回调,但从来没有响应
值。那么,您实际上想要实现什么?@Bergi试图捕获数据,如请求正文、请求标头、响应正文等,以写入SQL中的日志。您应该在发送响应时写入该日志,而不是在处理错误之后。如果发生错误,您当然需要将不同的数据捕获到日志中最后
不是这样做的正确位置除了然后
之外,还有其他动词可以用来帮助打破日志范围内的视觉流吗?“然后”通常被归类为副词,而不是动词:-)