承诺链基本问题

Dav*_*ave 3 javascript node.js promise bluebird

我正在努力了解Promises.我创建了一些有效的承诺链和其他没有的承诺链.我取得了进步,但显然缺乏基本概念.例如,以下承诺链不起作用.这是一个愚蠢的例子,但显示了问题; 我试图在链中使用Node的函数randomBytes两次:

var Promise = require("bluebird");
var randomBytes = Promise.promisify(require("crypto").randomBytes);

randomBytes(32)
.then(function(bytes) {
    if (bytes.toString('base64').charAt(0)=== 'F') {
        return 64;   //if starts with F we want a 64 byte random next time
    } else {
        return 32;
    }
})
.then(randomBytes(input))
.then(function(newbytes) {console.log('newbytes: ' + newbytes.toString('base64'));})
Run Code Online (Sandbox Code Playgroud)

这里出现的错误是" input未定义".我想做一些不能(或不应该)做的事吗?

Ber*_*rgi 5

您总是需要将回调函数传递给then().它会被附加到它的承诺的结果调用.

您当前正在randomBytes(input)立即呼叫,(如果input已定义)将通过承诺.你需要通过一个函数表达式,只是得到input作为它的参数:

.then(function(input) {
    return randomBytes(input);
});
Run Code Online (Sandbox Code Playgroud)

或者直接传递函数本身:

randomBytes(32)
.then(function(bytes) {
    return (bytes.toString('base64').charAt(0)=== 'F') ? 64 : 32;
})
.then(randomBytes)
.then(function(newbytes) {
    console.log('newbytes: ' + newbytes.toString('base64'));
});
Run Code Online (Sandbox Code Playgroud)