codestruggle
codestruggle

Reputation: 539

How to return plain values from bluebird promises?

I am new to promises. I am using Bluebird promises for running an async function in this fashion.

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 is an async operation which takes time.

After running this I am getting this exception.

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

Can't I return something from .then() and that would also be a promise. What is the correct way of returning values from promise functions ?

Upvotes: 3

Views: 1957

Answers (2)

Shanoor
Shanoor

Reputation: 13662

sdgluck gave you the answer but you can improve your code a bit more, you're using Bluebird so you can promisify 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);
});

Upvotes: 1

sdgluck
sdgluck

Reputation: 27217

You can indeed return a Promise within a then to pass execution to another asynchronous operation...

Whenever you want to do this, you must return the Promise. Here, that means returning the Promise that is created within getCreatedContract:

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

Upvotes: 3

Related Questions