2017-04-03 130 views
1

目前,我正在使用express和mongoose處理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 
    }) 
}) 
相關問題