如何打破`then`函数中的承诺

在这里,说我们有一个用户注册请求,我们要检测用户名是否已经是令牌(让我们假设数据是有效的),如果是,继续:

User .getByName(name) .then(function (user) { // if user is not null, which means the username is already token if (user !== null) return res.json({errorCode: 1001}) }) .then(function() { // Oops, the previous return is captcha here // how to break the promise and return the request var user = new User({ name: name }) }) 

感谢帮助

尝试下面的AS。 这是使用承诺的正确方法。

 var when = require('when'); checkUser(name) .then(function () { var user = new User({ name: name }) }, function (error) { // handle error here }) } var function checkUser(name){ var deferred = when.defer(); User.getByName(name,function(user){ user === null ? deferred.resolve() : deferred.reject(new Error('Username alreay token')) }); return deferred.promise; } 

为了避免你的第二个电话,你需要使第一个失败。 只要添加作为function(user)的最后一行throw 'User exists'then下一个进入拒绝path,你没有设置。

我承认,它是一个丑陋的方法,但它会工作! ;)

如果你不能解决你的承诺,你应该拒绝它:

 User.getByName(name).then(function(existing) { // If user already exists, we should return // rejected promise with good rejection reason if (existing !== null) return reject { message: 'User already exists', errorCode: 1001, status: 403 }; var user = new User({ name: name }); // ... some staff .. return user.save(); }).then(function(user) { // ... some other staff ... res.json(user); }).otherwise(function(err) { // Something bad happened somewhere in the chain res.status(err.status || 400).json({ message: err.message errorCode: err.errorCode }); }) 

在我的示例中,我使用通用拒绝处理程序向客户端发送错误响应,因为无论发生什么事情,我们都应该发送一些消息。

在我的例子中reject是一个返回被拒绝的函数的函数。 大多数promise库都有这样的函数(比如when.rejectQ.reject ),但是你可以用build-in throw语句来replace它。