2017-04-03 14 views
1

現時点では、私はエクスプレスとモンゴースでRESTful-APIに取り組んでいます。NodeJS:メソッドの終了時に未処理のプロミス拒否

まず、私の方法:

public create() : Promise<UserDocument> { 
    return new Promise((user) => { 
     User.exists(this.username).then((exists) => { 
      if (exists) { 
       throw Errors.mongoose.user_already_exists; 
      } else { 
       UserModel.create(this.toIUser()).then((result) => { 
        user(result); 
       }).catch(() => { 
        throw Errors.mongoose.user_create 
       }); 
      } 
     }).catch((error) => { 
      throw error; 
     }) 
    }); 
} 

私はこの方法を実行したときに、私は未処理の約束拒否を取得します。

User.fromIUser(user).create().then(() => { 
    return response.status(200).send({ 
     message: "Created", 
     user 
    }); 
}).catch((error) => { 
    return response.status(500).send({ 
     message: error 
    }); 
}); 

のフルスタックトレース:私はこの状況を回避するにはどうすればよい

(node:23992) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): User already exists 
(node:23992) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 

私はこのようなメソッドを実行すると、私はエラーを扱う場合でも、これはどうなりますか?あなたの助けのための

おかげで、 felixoi

答えて

1

は私が解決策を見つけました!約束を作成するために "解決、要求"を使用してください。あなたは今メソッドを呼び出す場合

public create() : Promise<any> { 
    return new Promise((resolve, reject) => { 
     User.exists(this.username).then((exists) => { 
      if (exists) { 
       reject(Errors.mongoose.user_already_exists); 
      } else { 
       UserModel.create(this.toIUser()).then((result) => { 
        resolve(result); 
       }).catch(() => { 
        reject(Errors.mongoose.user_create); 
       }); 
      } 
     }).catch((error) => { 
      reject(error); 
     }) 
    }) 
} 

あなたはcatch()メソッドを使用することができますし、すべての作品:ここ

は今私の方法です!このように呼び出す:

User.fromIUser(user).create().then((user) => { 
    return response.status(200).send({ 
     message: "Created", 
     user 
    }); 
}).catch((error) => { 
    return response.status(500).send({ 
     message: error 
    }) 
}) 
関連する問題