Promise chain fundamental issue

2019-05-14 00:24发布

问题:

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?

回答1:

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.

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