Skip to content

Instantly share code, notes, and snippets.

@colin-han
Last active July 12, 2019 06:13
Show Gist options
  • Save colin-han/39c34ee67c995aad92a519ccbc86f510 to your computer and use it in GitHub Desktop.
Save colin-han/39c34ee67c995aad92a519ccbc86f510 to your computer and use it in GitHub Desktop.
P2M training exam
let userId = 10;
let User = {
create: function (user) {
return new Promise((resolve) => {
setTimeout(() => {
let r = {
id: userId++,
name: user.name
}
console.log(JSON.stringify(r));
return resolve(r);
}, 1000);
});
}
}
let projectId = 20;
let Project = {
create: function (project) {
return new Promise((resolve) => {
setTimeout(() => {
let r = {
id: projectId++,
name: project.name,
onwerId: project.ownerId,
}
console.log(JSON.stringify(r));
return resolve(r);
}, 1000);
});
}
}
let taskId = 30;
let Task = {
create: function (task) {
return new Promise((resolve) => {
setTimeout(() => {
let r = {
id: taskId++,
title: task.title,
projectId: task.projectId,
assignTo: task.assignTo
}
console.log(JSON.stringify(r));
return resolve(r);
}, 1000);
});
}
}

使用Node.JS (版本>= 8)完成下题:

假设系统提供了三个函数:

  • Project.create({name: 'P1', ownerId: 1}) 函数
    在数据库中的Project表中创建一条记录。函数返回一个Promise对象。resolve方法的参数是一个Project对象:{id: 1, name: 'P1', ownerId: 1}
  • Task.create({projectId: 1, title: 'T1', assignTo: 1})函数
    在数据库中的Task表中创建一条子记录。这个记录通过projectId和Project表关联。函数返回Promise对象,resolve对象例如:{id: 1, projectId: 1, title: 'T1', assignTo: 1}
  • User.create({name: 'U1'})函数
    在数据库中的User表中创建一条记录。{id: 1, name: 'U1'}

model.js是上面三个函数的实现,请通过调用其中的方法完成下面的练习。

实现一段Javascript代码,创建如下的数据库记录。

  U1 -> User {name: 'U1'}
  U2 -> User {name: 'U2'}
  P1 -> Project {name: 'P1', ownerId: U1.id}
  T11 -> Task {projectId: P1.id, assignTo: U1.id, title: 'T11'}
  T12 -> Task {projectId: P1.id, assignTo: U2.id, title: 'T12'}
  P2 -> Project {name: 'P2', ownerId: U2.id}
  T21 -> Task {projectId: P2.id, assignTo: U1.id, title: 'T21'}
  T22 -> Task {projectId: P2.id, assignTo: U2.id, title: 'T22'}

其中 projectId: P1.id表示,创建时需要将之前创建的P1对象的id属性作为新对象的属性的值。

程序运行输出应该类似下面内容:(注:顺序不做要求)

{"id":10,"name":"U1"}
{"id":11,"name":"U2"}
{"id":20,"name":"P1","onwerId":10}
{"id":21,"name":"P2","onwerId":11}
{"id":30,"title":"T11","projectId":20,"assignTo":10}
{"id":31,"title":"T12","projectId":20,"assignTo":11}
{"id":32,"title":"T21","projectId":21,"assignTo":10}
{"id":33,"title":"T22","projectId":21,"assignTo":11}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment