0

I have this function that call a new one with _.map function that cycle each element or array
an than it could push items in Apify Storage, but the element of dataset is ever 0.
Why?

const Apify = require('apify')
const _ = require('underscore');

Apify.main(async () => {
    let item = {}
    let array = []

    const dataset = await Apify.openDataset('dataset2', {forceCloud: true});

    await mapping([1, 2, 3, 4, 5]);


    function mapping(array){
        _.map(array, async function (el) {
            console.log("====")
            console.log(el)
            console.log("====")
            await dataset.pushData(item) // <---- no items pushed
        })
    }
});

this is the screen: apify storage

Mariano
  • 473
  • 3
  • 12
  • Change the `const dataset` to `let dataset` or `var dataset`. – Trishant Pahwa Apr 29 '22 at 08:16
  • @TrishantPahwa how would that help? OP has a problem with async here, not scoping or reassignment. – ggorlen Apr 29 '22 at 14:40
  • 1
    @PappaLardo please don't use `map` for side effects. Use `forEach` if you're going to ignore the return value of `map`. This saves memory, object allocation/garbage collection and is more idiomatic/understandable to humans as to your intent. The `async` callback is in another promise chain than the enclosing function, so it runs after the current `async` function finishes executing. See [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) which applies equally to `map`. The solution is `for .. of` or `Promise.all`. – ggorlen Apr 29 '22 at 14:43

1 Answers1

1

The normal map function doesn't support async/await. Either accumulate into a new array and push that or use for (const ... of ...) loop

Lukáš Křivka
  • 953
  • 6
  • 9