filipbarak
filipbarak

Reputation: 1905

Cannot use async/await on MongoDB Model, even though it returns Promise?

I have a function which gets a user inventory, and then each of its element's price property with the Price gotten from a Price Collection.

Here it is (not the whole functon, but I'm getting the error here):

async function updateUserInventory(inventory, userDetails, socket) {
    let newArray = await inv.map(item => {
        let price = await Price.findOne({ market_hash_name: item.market_hash_name });
        return {
            price: price.price
        }
        logger.debug(JSON.stringify(item, null, 2));
    });

    socket.emit('user inv', { items: newArray });

Now as per the Mongo Docs, you may call Price.findOne with a callback, but you also can call it with a promise (.then()). Which means you SHOULD be able to also call it with await since it returns a promise. But alas, I'm getting an error which is this:

D:\code\some-api\api\helpers\priceUpdater.js:129
        let price = await Price.findOne({ market_hash_name: item.market_hash_name });
                          ^^^^^

SyntaxError: Unexpected identifier
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:607:28)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)

It works without the await keyword, but I cannot use it like that because then I'll have problems with asynchronicity.

Maybe I am not using async/await properly. Any help?

Upvotes: 0

Views: 272

Answers (1)

filipbarak
filipbarak

Reputation: 1905

For anyone that encounters the same problem (using await inside a .map or any JS array iterator function), I solved it by calling Promise.all on the .map and then async on the element being iterated. Thanks to @georg for the pointer.

async function updateUserInventory(inventory, userDetails, socket) {
    let newArray = await Promise.all(inv.map(async (item) => {
        let price = await Price.findOne({ market_hash_name: item.market_hash_name });
        return {
            price: price.price
        }
        logger.debug(JSON.stringify(item, null, 2));
    }));

    socket.emit('user inv', { items: newArray });

Upvotes: 0

Related Questions