The use of promises there is much more complicated than necessary. Remember that then
(and catch
and finally
) return new promises that are settled based on what their handlers return. new Promise
within a then
(or catch
or finally
) handler is almost never necessary; just return whatever you would resolve that promise with (a value or another promise), and the promise returned by then
et. al. will be resolved to it.
That chain should look like this, if I assume AWS.config.update()
is synchronous:
function deploy() {
return sts.assumeRole().promise()
.then(() => {
AWS.config.update();
})
.then(() => fsPromise.readFile(packageLocation))
.then(() => s3.upload().promise())
.then(() => ebs.createApplicationVersion().promise())
.then(() => ebs.createEnvironment().promise());
}
Each step in that chain will wait for the previous step to complete.
If you don't want deploy
to fulfill its promise with the fulfillment value of ebs.createEnvironment().promise()
, then add a final then
handler:
.then(() => ebs.createEnvironment().promise())
.then(() => { });
}
(I'll assume you want to do that for the following examples.)
Or like this if AWS.config.update()
is asynchronous and returns a promise:
function deploy() {
return sts.assumeRole().promise()
.then(() => AWS.config.update())
.then(() => fsPromise.readFile(packageLocation))
.then(() => s3.upload().promise())
.then(() => ebs.createApplicationVersion().promise())
.then(() => ebs.createEnvironment().promise())
.then(() => { });
}
Or, of course, in any relatively recent version of Node.js (I'm guessing from fsPromise
and just general context that this is Node.js), you could use an async
function:
async function deploy() {
await sts.assumeRole().promise();
await AWS.config.update(); // Or without `await` if it is synchronous and doesn't return a promise
await fsPromise.readFile(packageLocation);
await s3.upload().promise();
await ebs.createApplicationVersion().promise();
await ebs.createEnvironment().promise();
}
Side note about this code, and code like it you posted in a comment:
return new Promise((resolve, reject) => {
AWS.config.update({
credentials: {
accessKeyId: data.Credentials.AccessKeyId,
secretAccessKey: data.Credentials.SecretAccessKey,
sessionToken: data.Credentials.SessionToken
}
});
resolve();
})
There's no reason to use new Promise
there. It doesn't convert the call to AWS.config.update
into an asynchronous call or anything like that. If for some reason you needed a promise there (you don't in this case, AKAICT), you'd use Promise.resolve
:
AWS.config.update(/*...*/);
return Promise.resolve();
But again, no need for that here. Remember that promises only provide a way to observe the result of an asynchronous process, they don't make a process asynchronous. (The only thing that they actually make asynchronous is observing the result.)