简体   繁体   中英

How to access await function variable outside function in Node.js

I am trying to implement an await function which local variable I am trying to access outside the function. However, I'm not getting the value which is defined inside function.

async CreateProduceRateAsset(data, callback) {
    // Create a new file system based wallet for managing identities.
    try {
        var TimeStamp = new Date();
        var TxId = '';
        var blockNumber = '';
        const result = await contract.submitTransaction('CreateProduceRateAsset', args);

        await network.addBlockListener('block-listener', (err, block) => {
            if (err) {
                console.log(err);
                return;
            }

            TimeStamp = block.data.data[0].payload.header.channel_header.timestamp;
            var Tx_id = block.data.data[0].payload.header.channel_header.tx_id;
            var BlockNO = block.header.number;

            console.log('TxId', Tx_id)
            console.log('blockNumber', BlockNO)

            TxId = Tx_id
            blockNumber = BlockNO

            return TimeStamp, Tx_id, BlockNO
        });

        console.log('Timestamp', TimeStamp)
        console.log('TxId 123', TxId)
        console.log('blockNumber 123', blockNumber)

        response.data = result
        return callback(response);
    } catch (error) {
        response.httpstatus = 404;
        response.message = `Failed to get MVP Price ${error.message} `;
        return callback(response);
    }
};

In the above code, I want to access Tx_id , Timestamp and BlockNO . For that, I am assigning a local variable to a global variable, however, I'm still getting the value of those as blank.

Could someone help me to get those values?

You have to put your return into a variable like this:

var data = await network.addBlockListener('block-listener', (err, block) => {
    if (err) {
        console.log(err);
        return;
    }

    TimeStamp = block.data.data[0].payload.header.channel_header.timestamp;
    var Tx_id = block.data.data[0].payload.header.channel_header.tx_id;
    var BlockNO = block.header.number;

    console.log('###########TxId#####################', Tx_id)
    console.log('###########blockNumber#####################', BlockNO)

    TxId = Tx_id
    blockNumber = BlockNO
    return {TimeStamp, Tx_id, BlockNO};
});
    
console.log('*************** Timestamp:: **********************', data.TimeStamp)
console.log('###########TxId#####################123', data.Tx_id)
console.log('###########blockNumber#####################123', data.BlockNO)

Now you can store all your values into data and put them into the desired variables.

if I understand network.addBlockListener is a callback-based API and not return a promise so you cant await it, I guessed that you use https://hyperledger.github.io/fabric-sdk-node/release-1.4/module-fabric-network.Network.html

Here is your code with my comments

async CreateProduceRateAsset(data, callback) {
  // Create a new file system based wallet for managing identities.
  try {
      var TimeStamp = new Date();
      var TxId = '';
      var blockNumber = '';
      const result = await contract.submitTransaction('CreateProduceRateAsset', args);
      // --> this api is callback based and wont not return a promise so you cant await it 
     await network.addBlockListener('block-listener', (err, block) => {
          if (err) {
              console.log(err);
              return;
          }
          TimeStamp = block.data.data[0].payload.header.channel_header.timestamp;
          // --> becasue you are inside a function these vars are not the same as the one ouside the call back , becasue they are scoped to this function 
          var Tx_id = block.data.data[0].payload.header.channel_header.tx_id;
          var BlockNO = block.header.number;
          console.log('###########TxId#####################', Tx_id)
          console.log('###########blockNumber#####################', BlockNO)
          TxId = Tx_id
          blockNumber = BlockNO
// --> you can only return one value in js, also this reurn is useless since you dont call this callback
// --> better way to get these vars outside the callback is to pass them to your own callbak like this `callback(response,TimeStamp, Tx_id, BlockNO)`
          return TimeStamp, Tx_id, BlockNO
      });
      console.log('*************** Timestamp:: **********************', TimeStamp)
      console.log('###########TxId#####################123', TxId)
      console.log('###########blockNumber#####################123', blockNumber)

      response.data = result
      return callback(response);
  } catch (error) {
      // if(error) throw error;
      // response.error = error;
      response.httpstatus = 404;
      response.message = `Failed to get MVP Price ${error.message} `;
      return callback(response);
  }

};

if you need to use async/await with network.addBlockListener you can use utils.promisify to convert it to promise-based API but I don't recommend it since this an event listener

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM