如何从bluebird承诺中返回普通值?

时间:2016-02-09 15:09:48

标签: node.js promise bluebird

我是承诺的新手。 我正在使用Bluebird的承诺以这种方式运行异步函数。

var contract_creation = function creation(contractName){
    return new Promise(function (resolve,reject){

        web3.eth.sendTransaction(
            {
                from: web3.eth.accounts[0],
                data:contractsJSON[contractName].bytecode,
                gas:gasprice

            },
            function(err, transactionHash){
                if(err){
                    reject(err);
                }else{
                    resolve(transactionHash);
                }
            }
        );
    });

}

var getCreatedContract = function getReceipt(name){
    contract_creation(name)
    .then(function(transactionHash){
        return web3.eth.getTransactionReceipt(transactionHash);
    });
}

getCreatedContract("Fund").then(function(receipt){
    console.log(receipt);
});

sendTransaction是一种需要时间的异步操作。

运行后我得到了这个例外。

getCreatedContract("Fund").then(function(receipt){
                          ^
TypeError: Cannot read property 'then' of undefined

我不能从.then()返回一些内容,这也是一个承诺。从promise函数返回值的正确方法是什么?

2 个答案:

答案 0 :(得分:3)

你确实可以在then内返回一个Promise来将执行传递给另一个异步操作......

每当你想要这样做时,你必须返回Promise。在这里,这意味着返回在getCreatedContract中创建的Promise:

var getCreatedContract = function getReceipt(name){
    return contract_creation(name)
//  ^^^^^^
        .then(function(transactionHash){
            return web3.eth.getTransactionReceipt(transactionHash);
        });
}

答案 1 :(得分:1)

sdgluck 为您提供了答案,但您可以更多地改进您的代码,您正在使用Bluebird,因此您可以宣传sendTransaction()

var Promise = require('bluebird');

var contract_creation = function creation(contractName) {
    // if you need this promisified function elsewhere, you can declare it globally
    var sendTransactionAsync = Promise.promisify(web3.eth.sendTransaction);

    return sendTransactionAsync({
        from: web3.eth.accounts[0],
        data: contractsJSON[contractName].bytecode,
        gas: gasprice
    });
}

var getCreatedContract = function getReceipt(name) {
    return contract_creation(name)
        .then(web3.eth.getTransactionReceipt); // << no need to wrap the function inside another function
}

getCreatedContract("Fund").then(function (receipt) {
    console.log(receipt);
});
相关问题