Reputation: 387
When chaining promises in Javascript, what happens if one function in the middle of the chain does not return anything, but still performs a async operation that needs to be completed before moving on?
Does the next 'then()' wait for the previous async function to resolve even though it is not passed any values?
EDIT: here's a application example:
connectDatabase()
.then(() => createTables())
.then(() => fillTables())
.then(() => selectTables)
.then(tables => showTables());
This code simply represents the creation of a SQLite database and some further operations to finally display the table values.
connectDatabase()
is a async function. Once the database is created, the function doesn't need to return anything since the database is stored in some global function (for use outside the promise chain). The next step doesn't need any arguments although it needs the database to be created to insert tables in it.
The createTables()
function creates some tables asynchronously and once it's done, it returns nothing and the next function can be called.
selectTables()
just uses the sql SELECT
command to store the table values in a variable and returns it to the next function.
showTables()
uses the table values that's passed on to it and displays on the screen.
Upvotes: 2
Views: 336
Reputation: 1298
If a function in the promise chain resolves a value, then the following function in the chain will have access to the resolved value. For example, in your example if createTables
resolved a value, then that resolved value would be available to the next function in the chain as an argument (in this case, (resolvedValue) => fillTables()
).
If it doesn't resolve a value (just calls resolve()
with no arguments, or simply doesn't return a value in the case of an async
function), then the following promise in the chain will simply not receive any arguments.
So, yes the next then
will always wait for the previous promise to resolve (whether it resolves with a value or not).
EDIT: Removed/corrected the first portion of my answer based on Lennholm's feedback (thank you!). then
will by default return a promise, so that will always be then-able
. If the callback function passed to then returns a promise, then then
's promise will resolve to the value that the callback resolves; if the callback doesn't return a promise, then then
will simply resolve the value that the callback returns.
For more info on this, checkout the following answer: https://stackoverflow.com/a/46142909/815086
Upvotes: 1