Promise chain fundamental issue

一笑奈何 提交于 2020-01-13 13:05:21

问题


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


来源:https://stackoverflow.com/questions/25431919/promise-chain-fundamental-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!