Skip to content
Advertisement

Perform an action after a promise.then callback

I’m trying to encapsulate some intialization / clean up code in a single Promise. What I want if to execute some code, execute the then and then execute some more code. This is what I came up with:

JavaScript

which gives me the following output in the terminal:

JavaScript

All good so far. However, when we make the callback async, it no longer works.

JavaScript

gives me this output:

JavaScript

I would have expected it to look like this:

JavaScript

How can I fix this? Is this even possible at all?

Advertisement

Answer

You can accept a callback that defines an asynchronous operation. Then it can be inserted into the middle of an promise chain:

JavaScript

It works even if there are multiple async steps to do in between, since you can simply chain them together:

JavaScript

The same can be done using async/await syntax:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement