I've written a function which ensures all objects in the items
array belong to the user
. This involves a database check, which results in the code being asynchronous. This code works, but feels sloppy. I'd appreciate a review and suggestions for how to improve it.
The main challenge I had with writing this was to use items.every() with Promises and I don't think the solution I came up with was very elegant. I spent quite a bit of time on it and couldn't think of a better way to do it.
Intuitively async/await feels like a good fit for this type of problem but I had difficulty applying it here.
function belongTo (user, items) {
return new Promise(resolve => {
resolve(items.every((item) => {
return new Promise((resolve, reject) => {
Item.findOne({ owner: user,
assetID: item.assetid,
appid: item.appid,
contextid: item.contextid,
marketHashName: item.marketHashName
}).then((item) => {
if (Object.keys(item).length !== 0) resolve(true)
else resolve(false)
}).catch(reject)
})
}))
})
}
I'm using the JavaScript Standard style guide.
Promise.all
to wait for all the promises to resolve. \$\endgroup\$ – Marc Rohloff May 13 '17 at 18:37