Nodejs mongodb's Transaction API 'withTransaction' 总是返回 null



我想从mongodb的withTransaction函数返回某些结果。然而,除了null之外,我似乎无法返回任何内容。

官方文件中记录了应该返还的承诺。

https://mongodb.github.io/node-mongodb-native/3.3/api/ClientSession.html

IMPORTANT: This method requires the user to return a Promise, all lambdas that do not
return a Promise will result in undefined behavior.

index.js

const mongodb = require('mongodb');
(async() => {
const client = await mongodb.connect(url);
const db = await client.db("testt");
const session = client.startSession()
const res =   session.withTransaction(async function() {
return new Promise((resolve, reject) => {
if(true) {
resolve('laughed')
} else {
reject(`not laughing`);
}
})
})
console.log('result here')   //result here
console.log(res)             //Promise { <pending> }
console.log(await res);      //null
}) ()

编辑:由于异步函数总是返回Promise。我用一个简单的字符串替换了new Promise(),但结果完全相同,令人困惑。

const res =   session.withTransaction(async function() {
return `laughed`
})

官方文档中记录了应该返回promise。

文件上说(强调我的(:

重要提示:此方法要求用户返回Promise,所有不返回Promise的Lambda都将导致未定义的行为。

您从回调返回的承诺不会从withTransaction返回。我看不到任何关于withTransaction返回值的描述。

当前实现似乎返回commitTransaction的结果作为withTransaction的返回值,如果提交成功,则该结果显示为null

我相信您的应用程序向驱动程序承诺的结果在这里被丢弃了。

因此,驾驶员的行为似乎与记录相符。

此行为更改是在此处请求的。

最新更新