0

The objective is to check for duplicate records in a MongoDB and return a new file object (filteredObj) that does not contain records already existed in the DB. Each record has a description key.

hasDuplicateDescription method returns a Promise that resolves to a true or false, true if there is no existing record.description in the DB, false otherwise. However, the returned filteredObj has the original fileObj content, without any filtering done.

  const filteredObj = fileObj.filter((record) => {
    return this.hasDuplicateDescription(record.description).then(
      (res) => {
        return res;
      }
    );
  });
  return filteredObj;

The solution below was the recommended solution for getting async function to work with array.filter in other posts but it does not work in my case as hasDuplicateDescription is an async function that requires each array element passed in by the array.filter method as its argument.

const results = await Promise.all(your_promises)
const filtered_results = results.filter(res => //do your filtering here)

Appreciate any advice on how to approach this problem.

Thank you!

1
  • if you need to collect all the filtered results, you have to wait on all the promises to finish anyways. async just wraps function's return in a promise, so just collect them all and feed it to Promise.all Commented Jun 5, 2020 at 0:43

1 Answer 1

1

You map each element in `your array to promise that resolves condition for filtering combine it with value filter by result of condition resolving and map to value:

const asyncFilter =  async (arr, asyncCheck) => (await Promise.all(arr.map(async (item) => [await asyncCheck(item), item]))).filter(([b]) => b).map(([, x]) => x)

asyncFilter(fileObj, (record) => this.hasDuplicateDescription(record.description))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.