1

I have the following function:

const bulkPreprocess = (files) => {

let bulkOps = []

files.map(doc => {
    parse(doc).then(content => {
        const sent = sentiment(content)
        bulkOps.push(sentiment)
        bulkOps.push({anotherobject})
    })
})
  return bulkOps
}

Which is called by a main function like so:

module.exports = (req, res) => {
    //parses post request with file uploads
    const form = new multiparty.Form()

    form.parse(req, (err, fields, allFiles) => {
        //called more than once
        const files = allFiles['files']
        let processed = bulkPreprocess(files).then(bulk => {
            console.log(bulk.length)  
            addToES(bulk)
        })
    })

    res.json({ success: true })
}

My problem is that since bulkPreprocess calls the parse function (which is async), I can't get it to wait until all the files are parsed before addToES is called. The parse function itself calls another function which is async (which is why I had to make it async).

The whole flow is like this:

Main -> bulkPreprocess -> (Parse -> parseDoc) -> return value from bulkPre -> addToES

I tried changing all the functions to async/await, I tried returning a promise inside the map function in bulkPreprocess. I tried callbacks. Nothing is working out.

Any advice?

2
  • That's not how .map() should be used. In your example that should be .forEach() instead. Why is this tagged async-await if you're not using them? Why don't you use Promise.all()? Commented Jan 28, 2019 at 12:32
  • I tried changing all the functions to async/await, I tried returning a promise inside the map function in bulkPreprocess - what exactly did you try and what did not work? What is sentiment? Is there a reason why form.parse is callback-based? Commented Jan 28, 2019 at 12:32

1 Answer 1

3

You need to return Promise from bulkPreprocess which resolves after your async parse so you need Promise.all to wait for all parse calls are finished

Edit: Now it's push objects to bulkOps and resolve with it after all parse are finished

const bulkPreprocess = (files) => {
    let bulkOps = [];
    return Promise.all(files.map(doc => {
        return parse(doc).then(content => {
            const sent = sentiment(content);
            bulkOps.push(sentiment);
            bulkOps.push({anotherobject});
        });
    })).then(() => bulkOps);
};
Sign up to request clarification or add additional context in comments.

10 Comments

The function actually pushes two objects to bulkOps. I just took one out in the post for brevity
This still calls addToES more than once
Impossible, Promise can be settled (resolved/rejected) only once
I think it has something to do with the main function that calls addToES
@ninesalt This IS posible :)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.