Update: This question was pretty misinformed. Basically before you read on, just understand that although I am already constructing fancy promisified routines to do work, I wasn't quite grasping the basic principles of promises and how to use them in an async/await context.
There are exactly two standard and important ways to achieve a continuation from one promise to the next, which is part of what I was asking for:
- promises can be chained to other promises with then()
- promises can be awaited in sequence within an
async
function context, and they will wait (hence "await") for completion before proceeding.
What I am asking for is if the first promise in a chain needs to be controlled or predicated, how can I express this cleanly?
I have some existing code which does stuff in a promise.
I am adding a new step to the process that has to happen before it, but conditionally.
Before:
let promise_manipulate_files = util.promisify(_async.eachOfLimit)(fs.readdirSync(directory), 5, (f, _i, cb) => { ... })
After (this code is wrong):
if (filesNeedToBeRenamed()) {
let promise_rename_files = Promise.all(fs.readdirSync(directory).map(
file => util.promisify(fs.rename)(file, amendedFilename(file))
.catch({ ... })
));
}
let promise_manipulate_files = util.promisify(_async.eachOfLimit)(fs.readdirSync(directory), 5, (f, _i, cb) => { ... })
The concern is that the second promise must not be allowed to begin until the first promise is completely finished.
This is the top level of my script.
Is the only practical way to get what I want to wrap the entire code in an async () => {}
closure and await
on the first promise?
The reason that the example is a little more complex than it could be minimally, is because if i show a minimal example, then it's pretty clear that the operations should just be performed synchronously. Indeed I am trying here to enforce a particular kind of synchronous boundary on these tasks.
I believe the crux of the issue here is that the if
condition prevents me from being able to directly chain manipulate_files
onto rename_files
by using .then()
!