我正在观看视频以学习 MongoDB Express.js VueJS Node.js (MEVN) 堆栈。
我想创建一个种子目录并使用 promise 函数
// const delay = require('delay')
const Promise = require('bluebird')
const songs = require('./songs.json')
const users = require('./users.json')
const bookmarks = require('./bookmarks.json')
const historys = require('./history.json')
sequelize.sync({ force: true })
.then( async function () {
await Promise.all(
users.map( user => {
User.create(user)
})
)
await Promise.all(
songs.map( song => {
Song.create(song)
})
)
//I have to add this line
// ---> await delay(1000)
await Promise.all(
bookmarks.map( bookmark => {
Bookmark.create(bookmark)
})
)
await Promise.all(
historys.map( history => {
History.create(history)
})
)
})
我有四个带种子的表要创建,最后两个表数据必须在前两个表数据之后创建。 (它们是外键)
但是我每次运行这个文件,都会先创建最后两个表的数据
我能防止这种情况的唯一方法是在它们之间添加 delay(1000)。
请问有没有什么有效的方法可以解决这个问题~
谢谢。
最佳答案
像这样的竞争条件总是由未正确链接 promise 引起的。
应该从 map
回调中返回一个 promise :
await Promise.all(
users.map( user => User.create(user))
);
等等
不从 map
返回值实际上总是错误的。可以通过使用 array-callback-return
ESLint rule 来防止。 .
如果 User.create(user)
等是具有默认配置的 Bluebird promise ,则不链接它们也会导致 this warning .
关于javascript - Bluebird promise 订单问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51517755/