0

I don't know why first it prints data return instead of after loop done

code

exports.put = async function (req, res, next) {
    const data = Array.from(req.body);
    let errors = false;
    data.forEach(async (update, index) => {
        try {
            const result = await TypeofAccount.findByIdAndUpdate(
                new mongoose.Types.ObjectId(update._id),
                {
                    $set: { name: update.name },
                },
                { new: true, runValidators: true },
            );
            console.log(index);
            if (!result) {
                errors = true;
                console.log('errors');
                return res.status(500).send();
            }
        } catch (e) {
            return res.status(500).send();
        }
    });
    console.log('data return');
    res.json(data);
};

  • data return
  • PUT /api//typeofaccount 200 5.551 ms - 202
  • 0
  • 1
  • 2
Indraraj26
  • 1,726
  • 1
  • 14
  • 29
  • 2
    Marking the callback function passed to `forEach()` as `async` only makes that callback return a promise, it doesn't make `forEach()` run asynchronously. – Lennholm Jul 01 '20 at 09:25
  • Thank you @BilalAkbar, it is working fine with for of, strange behavior of javascript, i have been thinking it should run after forEach – Indraraj26 Jul 01 '20 at 09:34
  • 1
    It's perfectly logical behavior once you understand how `async-await` actually works. Keep in mind that unlike `for-of`, `forEach()` isn't a language feature, it's part of the array API. – Lennholm Jul 01 '20 at 09:45

2 Answers2

0

The .for each function runs asynchronously and that is why you can see the console.log which is after the loop get printed first

0

this problem happened becouse you are use forEach loop , asyc await not working with forEach , to avoid this problem your code block should be like

for(let i in data){
try {
            const result = await TypeofAccount.findByIdAndUpdate(
                new mongoose.Types.ObjectId(data[i]._id),
                {
                    $set: { name: data[i].name },
                },
                { new: true, runValidators: true },
            );
            console.log(i);
            if (!result) {
                errors = true;
                console.log('errors');
                return res.status(500).send();
            }
        } catch (e) {
            return res.status(500).send();
        }
}
y.ilsaqa
  • 86
  • 4