nozzang
nozzang

Reputation: 41

How can i get value from object in Array with Promise?

[
  Promise {
    {
      filename: '5A756579-9191-49D0-8B02-89B0A232FAA4_1_102_o.jpeg',
      mimetype: 'image/jpeg',
      encoding: '7bit',
      createReadStream: [Function: createReadStream]
    }
  },
  Promise {
    {
      filename: '54DF4C9A-A7E3-4ABE-BC22-6E4C3C73236E.jpeg',
      mimetype: 'image/jpeg',
      encoding: '7bit',
      createReadStream: [Function: createReadStream]
    }
  }
]

i want to get filename value from this data like this;

{ 5A756579-9191-49D0-8B02-89B0A232FAA4_1_102_o.jpeg, 54DF4C9A-A7E3-4ABE-BC22-6E4C3C73236E.jpeg }

How can I solve this problem?

Upvotes: 0

Views: 51

Answers (1)

DecPK
DecPK

Reputation: 25401

SOLUTION 1

Since you have an array of promises then you can use Promise.all

const promise1 = Promise.resolve({
    filename: '5A756579-9191-49D0-8B02-89B0A232FAA4_1_102_o.jpeg',
    mimetype: 'image/jpeg',
    encoding: '7bit',
});

const promise2 = Promise.resolve({
    filename: '54DF4C9A-A7E3-4ABE-BC22-6E4C3C73236E.jpeg',
    mimetype: 'image/jpeg',
    encoding: '7bit',
});

async function getFileNames() {
    const promiseArr = [promise1, promise2];
    const resultArr = await Promise.all(promiseArr);
    const result = resultArr.map((o) => o.filename);
    console.log(result);
}

getFileNames();

NOTE: Promise.all also returns a promise and it will only be resolved if all of the promises are resolved. If any of the promise gets rejected in Promise.all then overall it will be rejected.

differences between Promise.all Promise.allsettled

SOLUTION 2

You can also use Promise.allSettled here. It will give you an array of objects and each object will contain two properties i.e status and value.

status can either be fulfilled or rejected and you can filter them all according to your requirement.

const promise1 = Promise.resolve({
    filename: '5A756579-9191-49D0-8B02-89B0A232FAA4_1_102_o.jpeg',
    mimetype: 'image/jpeg',
    encoding: '7bit',
});

const promise2 = Promise.resolve({
    filename: '54DF4C9A-A7E3-4ABE-BC22-6E4C3C73236E.jpeg',
    mimetype: 'image/jpeg',
    encoding: '7bit',
});

async function getFileNames() {
    const promiseArr = [promise1, promise2];
    const resultArr = await Promise.allSettled(promiseArr);
    const result = resultArr.filter(({ status, value }) =>
        status === 'fulfilled' ? value : false
    );
    console.log(result);
}

getFileNames();

Upvotes: 2

Related Questions