Akira
Akira

Reputation: 273

Array returns nothing with async and await in Nodejs

I am new to the node.js and I need to extract all the snapshot IDs by running the following function:

const createSnapshots = async volumes => {
  try {
    let arr = [];
    volumes.Volumes.map(async (vol, i) => {
      let volId = vol.VolumeId;
      let isEncrypted = vol.Encrypted;
      let tags = vol.Tags;
      console.log(i, volId, isEncrypted, tags);
      if (!isEncrypted && tags[0].Value === 'Test') {
        // console.log(volId);
        let params = {
          Description: 'test snapshot',
          VolumeId: volId
        };
        let snapshots = await ec2.createSnapshot(params).promise();
        let snapshotId = snapshots.SnapshotId;
        ec2.waitFor(
          'snapshotCompleted',
          (params = { 'snapshot-id': snapshotId })
        );
        arr.push({ snapshotId, tags });
        console.log(arr);
      }
    });
    console.log(arr);
  } catch (error) {
    console.error(error);
  }
};

However, the array returns as empty. If I console log the array in the if statement, it returns data. I know there is something to deal with the promise. However, I have no idea where I have to modify the code. Thanks

Upvotes: 0

Views: 58

Answers (1)

Suman Kumar Dash
Suman Kumar Dash

Reputation: 704

The main problem is .map() function is async. Hence you should use an await. Then only you can get arr value outside of if. It should be something like that.

const createSnapshots = (volumes ) => {
const arr = volumes.Volumes.map(async (vol, i) => {
  let volId = vol.VolumeId;
  let isEncrypted = vol.Encrypted;
  let tags = vol.Tags;
  console.log(i, volId, isEncrypted, tags);
  if (!isEncrypted && tags[0].Value === 'Test') {
    // console.log(volId);
    let params = {
      Description: 'test snapshot',
      VolumeId: volId
    };
    let snapshots = await ec2.createSnapshot(params).promise();
    let snapshotId = snapshots.SnapshotId;
    ec2.waitFor(
      'snapshotCompleted',
      (params = { 'snapshot-id': snapshotId })
    );
    return {
        tags : tags,
        snapshotId : snapshotId 
    }
  }
 });
 return Promise.all(arr);
}

Through this way you will get return of your array.

Upvotes: 2

Related Questions