javascript - Bluebird promise 传播方法返回 TypeError

标签 javascript node.js promise sails.js bluebird

我不知道在 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 之后的其余代码,因为它并不是真正相关的,而且这是在返回错误之前停止执行的地方。

我只想将变量resultstoken 传递给.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/

相关文章:

node.js - 如何处理feathersjs钩子(Hook)内的 promise ?

javascript - cryptoJS 解密/解密消息 AES CFB 模式

javascript - 如何将javascript对象映射到mvc模型?

node.js - dustjs 或多个参数的条件

javascript - 显示来自 Meteor 1.0 的数据

javascript - 使用身份验证中间件表达资源?

javascript - 新调用时不重置默认操作

javascript - javascript中抽象方法的目的是什么?

javascript - Mongoose 静态方法返回一个 Bluebird promise

node.js - 异步 Mocha 测试(使用 Chai 断言库)应该失败,但被标记为通过