为何Prisma ORM的update函数需调用.then()才执行数据库更新?
问题:为何Prisma的update必须调用.then()才能生效?
我在API中使用Prisma ORM的prisma.instance.update()函数时遇到了不可预测的行为:如果不调用.then()方法,update函数完全不会更新数据库;将所有这些Promise用Promise.all包裹并调用它的.then()方法后,更新才正常生效。想知道为什么必须调用.then()才能让Promise resolve?
相关代码:
else if(allocationsGroupId != null) prisma.allocation.findMany({ where: { allocationsGroupId } }).then((allocations) => { const commonPercent = allocations.reduce((total, allocation) => total + allocation.percent, 0) Promise.all(allocations.map((allocation) => prisma.allocation.update({ where: { id: allocation.id }, data: { money: allocation.money + amount * allocation.percent / commonPercent} }))).then() })
原因解析
Prisma操作本质是异步Promise:Prisma的所有数据库操作(包括
update)都返回Promise,这类异步操作不会立刻执行完成,而是进入JavaScript的异步任务队列等待后续执行。未被“等待”的Promise可能中途终止:在API请求场景中,如果只是创建了Promise但没有任何代码去等待它完成(比如不用
.then()、await),当前的请求处理逻辑会在同步代码跑完后直接结束,Node.js的事件循环不会等待异步队列里的数据库操作完成,导致Prisma的update请求还没来得及和数据库完成交互就被终止,自然看不到数据库更新。.then()的作用是触发等待逻辑:调用.then()(或用await)相当于告诉程序“要等这个异步操作做完再继续”。你用Promise.all()打包所有update的Promise后调用.then(),就是让程序等待所有更新操作全部执行完毕,确保Prisma有足够时间完成数据库更新。
更清晰的替代写法
用await替代.then()可以让代码逻辑更直观,效果完全一致(注意外层函数需要标记为async):
else if(allocationsGroupId != null) { const allocations = await prisma.allocation.findMany({ where: { allocationsGroupId } }); const commonPercent = allocations.reduce((total, allocation) => total + allocation.percent, 0); await Promise.all(allocations.map(allocation => prisma.allocation.update({ where: { id: allocation.id }, data: { money: allocation.money + amount * allocation.percent / commonPercent } }) )); }
内容的提问来源于stack exchange,提问作者MindW1n
相关产品推荐
相关产品推荐

