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.
CodePudding user response:
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)})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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();
}
}