我不知道在 Sails.js 模型上使用 Bluebird promises 时我是否没有正确使用 .spread
方法.这是我拥有的:
transactionAsync('BEGIN')
.then(function() {
return Model.findOne({ id: 5) });
})
.then(function(results){
if(!results) {
return res.notFound();
}
crypto.randomBytes(24, function(err, buf) {
if(err) throw new Error(err);
var token = buf.toString('hex');
// This is where it fails
return [results, token];
});
})
.spread(function(results, token) {
// It doesn't get to log these
console.log(results, token);
...
})
...
在第二个 .then
返回 [results, token]
之后(在加密回调内部),它吐出
[TypeError: expecting an array, a promise or a thenable]
我删除了 .spread
之后的其余代码,因为它并不是真正相关的,而且这是在返回错误之前停止执行的地方。
我只想将变量results
和token
传递给.spread
中的函数。我做错了什么?
任何帮助都很棒。谢谢。
最佳答案
After returning
[results, token]
on the second.then
那不是你在做什么。您正在返回加密回调内部,这是没有意义的。没有人知道这个回调,您实际上也没有从 then
回调返回
任何东西。
first rule promise 发展是promisify底层 API,以便您可以实现纯粹的 promise 。
var crypto = Promise.promisifyAll(crypto);
// or specifically:
var randomBytes = Promise.promisify(crypto.randomBytes);
现在我们可以遵循规则 3b 并实际从 then then
回调返回一个(promise)结果:
…
.then(function(results) {
if (!results) {
return res.notFound();
}
return crypto.randomBytesAsync(24) // returns a promise now!
// ^^^^^^
.then(function(buf) {
var token = buf.toString('hex');
return [results, token];
});
})
.spread(function(results, token) {
console.log(results, token);
…
})
关于javascript - Bluebird promise 传播方法返回 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29424285/