简体   繁体   中英

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?

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 ie 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();

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