Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
async/await access previous result and pass it to next operation

If my function uses two independent async operations, then an unreachable backend between the first and second operation would result in a (stored) and b (not stored).

try {
  const a = await createA();
  // error: backend not available
  const b = await createB();
}

I could use await Promise.all(), to wait until all promises are resolved, so either both are stored or none are stored.

await Promise.all([createA(), createB()]);

But how to solve this situation, if my second async operation depends on the result of the first one.

try {
  const a = await createA();
  // error: backend not available
  const b = await createB({ _id: a._id });
}

Is there any way to handle this with using async and await and not chained .then() statements?

Edit: I expect that a and b will be created or none of both. Both operations a and b saves documents via mongoose driver to a mongodb database.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You want to create a promisePipe instead using reduce. With reduce you can use the output of the previous operation as input for the next operation.

For example:

const myPromise = async n => {
    return Promise.resolve(1 * n)
}

const myPromise2 = async n => {
    return Promise.resolve(2 * n)
}

const promiseReduce = async (prevPromise, currPromise) => {
  const prevResult = await prevPromise;
  return currPromise(prevResult).catch(err => {
    throw err // throw a internal error server here
  });
}
    
const promisePipe = (...fns) => {
    return fns.reduce(promiseReduce, Promise.resolve(1))
}

promisePipe(myPromise, myPromise2).then(e => { console.log(e)})

about 4 years ago · Juan Pablo Isaza Report

0

if the second function depends upon the first result then you can use the below snippet:

try {
     const a = await createA();
       // null and if id is exists than call createB
        if (a && a.id) {
            const b = await createB();
        }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!