Realm,删除对象后访问对象属性



我正在删除一个Realm db对象,但我想在删除后访问它的值,以便在其他处理中使用它。我的代码是这样的:

const theObject = realm.objects('Products').filtered("_id == $0", "61bba17fc7e82eaae53527de")
//the fetched theObject(response) looks like this: 
[{_id:'61bba17fc7e82eaae53527de', name: 'Sugar'}]
var productName = theObject[0].name
realm.write(() => {
realm.delete(theObject)
})
return productName //I want to use this productName here to do some other stuffs

我想使用/返回productName来做一些其他事情,但当我尝试访问它时,我发现它未定义为null

我认为这是因为对象已被删除,因此无法访问productId,但我想知道为什么会这样,因为我在删除前分配该id时已经捕获了该id。即productName = theObject[0].name

现在,我的问题是,我如何仍然可以获得/访问/返回该productName?

这应该是不可能的。注释掉delete,并控制台日志productName,以确保事情按照您认为的方式进行。

此外,看起来您缺少productName 的var/lit/const

const productName = theObject[0].name

编辑:

由于这些都是异步操作,real.objects('Prodcuts')可能会在竞争中输给realm.delete()。您可以通过在尝试删除之前等待访问请求来解决此问题。