承诺链基本问题

承诺链基本问题

问题描述:

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

I'm trying to understand Promises. I've create some promise chains that work and others that don't. I've made progress but am apparently lacking a basic concept. For example, the following promise chain doesn't work. It's a silly example, but shows the issue; I'm trying to use Node's function randomBytes twice in a chain:

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'));})

这里出现的错误是输入未定义。我试图做一些不能(或不应该)做的事情吗?

The error that arrises here is "input is undefined." Am I trying to do something that can't (or shouldn't) be done?

你总是需要通过一个回调功能然后()。它将被附加到您的承诺的结果调用。

You always need to pass a callback function to then(). It will be called with the result of the promise that you attach it to.

您当前正在调用 randomBytes(输入)立即,(如果输入已定义)将传递一个承诺。您需要传递一个函数表达式,只需获取 输入作为参数:

You're currently calling randomBytes(input) immediately, which (if input was defined) would have passed a promise. You need to pass a function expression that just gets the input as its parameter:

.then(function(input) {
    return randomBytes(input);
});

或者直接传递函数本身:

Or just pass the function itself directly:

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'));
});