-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy path3. async_promise.js
32 lines (31 loc) · 1.25 KB
/
3. async_promise.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const { users, restaurants } = require('./data')
const RestaurantModel = require('./restaurant')
const UserModel = require('./user')
const mongoose = require('mongoose')
mongoose.connect("mongodb://localhost/restaurant_list_async_promise")
const db = mongoose.connection
// 連接資料庫: db.once('open', callback)
// promise是ES6提供來解決callback function造成callback hell的方法,
// 被包覆在promise內的function,會保證在呼叫resolve後才會執行.then裡面的程序,
// 避免callback會一直往下層寫,造成不好閱讀的程式碼
db.once('open', () => {
new Promise((resolve, _reject)=>{
for (const [user_index, user] of users.entries()) {
//創建使用者資料(user): model.create
UserModel.create({
...user
}).then((user)=>{
//對每個user建立相對應餐廳資料
return RestaurantModel.create(restaurants)
}).then(()=>{
resolve()
}).catch( error => {
console.log(error)
})
}
}).then(()=>{
//等待所有使用者的餐廳資料創建完成
console.log("所有使用者與餐廳資料創建完成")
process.exit()
})
})