Skip to content

Instantly share code, notes, and snippets.

@afucher
Created January 25, 2017 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afucher/3b5b8aabccb831f469ea6014d0e661f9 to your computer and use it in GitHub Desktop.
Save afucher/3b5b8aabccb831f469ea6014d0e661f9 to your computer and use it in GitHub Desktop.
GroupController.addStudent = (id, student_id) => {
return Group.findById(id)
.then((g) => new Promise((resolve, reject) => {
if(g){
resolve(g);
}else{
reject('??');
}
}));
};
@rafaeljesus
Copy link

I would write ir like:

GroupController.addStudent = (id, student_id) => {
  return Group.findById(id).then((g) => new Promise((resolve, reject) => {
    if (g) {
      resolve(g);
    } else {
      reject('??');
    }
  }));
}

So consumers of controller may call as GroupController.addStudent(params).then(....)

Also take a 👀 at this promises examples

@awerlang
Copy link

Pode encadear as promises através do then():

GroupController.addStudent = (id, student_id) => {
    return Group.findById(id)
        .then(g => {
            if (!g) {
                throw new Error('??');
            }

            return Model.create(...);
        });
};

Ou melhor ainda, faça findById rejeitar a promise se não encontrar o objeto com a id:

GroupController.addStudent = (id, student_id) => {
    return Group.findById(id)
        .then(g => {
        // g é um objeto
        });
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment