最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

Nodejs mongodb的Transaction API`withTransaction`始终返回null

IT培训 admin 13浏览 0评论

Nodejs mongodb的Transaction API`withTransaction`始终返回null

我想从mongodb的withTransaction函数返回某些结果。但是,我似乎只返回了null。

官方文档中记录了应返还诺言。

.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`
})

我想从mongodb的withTransaction函数返回某些结果。但是,我似乎无法返回任何东西,除了null之外。官方文档中记录了...

回答如下:

官方文档中记录了应返还诺言。

Nodejs mongodb的Transaction API`withTransaction`始终返回null

我想从mongodb的withTransaction函数返回某些结果。但是,我似乎只返回了null。

官方文档中记录了应返还诺言。

.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`
})

我想从mongodb的withTransaction函数返回某些结果。但是,我似乎无法返回任何东西,除了null之外。官方文档中记录了...

回答如下:

官方文档中记录了应返还诺言。

发布评论

评论列表 (0)

  1. 暂无评论