I have an error TypeError: cars.map(...).then is not a function
. I want terminate connection when update the color.
cars.map(function (item, i) {
if (item.color === 'red') {
updateColor(item.id)
}
}).then(() => connection.end())
I have an error TypeError: cars.map(...).then is not a function
. I want terminate connection when update the color.
cars.map(function (item, i) {
if (item.color === 'red') {
updateColor(item.id)
}
}).then(() => connection.end())
Share
Improve this question
asked Oct 10, 2019 at 8:45
user10408704user10408704
3
|
2 Answers
Reset to default 11This answer only applies in case updateColor
is asynchronous and indeed returns a Promise
object.
.map
returns an array of something, not a Promise
. What you can do, is building an array of Promise
using .map
and then resolve them all using Promise.all
and then deal with the result.
The following code will execute all updateColor
, wait until they are done and then stop the connection.
Promise.all(cars.map((item, i) => {
if (item.color === 'red') {
return updateColor(item.id);
}
return false;
}))
.then(() => connection.end())
Using async/await
instead of Promises
await Promise.all(cars.map((item) => {
if (item.color === 'red') {
return updateColor(item.id);
}
return false;
}));
connection.end();
using reduce
instead of map
await Promise.all(cars.reduce((tmp, x) => (x.color === 'red' ? [
...tmp,
updateColor(x.id),
] : tmp), []));
connection.end();
There are a couple of issues there:
There's no reason to use
map
when you aren't using the array it creates. To loop through the array, useforEach
or any of several other mechanisms.map
is a fully synchronous function. To do something after it, just...do the thing after it.then
is a method of promises (well, thenable).map
returns an array, not a promise.
So:
for (const item of cars) {
if (item.color === 'red') {
updateColor(item.id)
}
};
connection.end();
If updateColor
does its work asynchronously and returns a promise, then see Grégory NEUT's answer.
map
works with Array only. Did you initializecars
as an array? againthen
also not work withmap
– Harish Commented Oct 10, 2019 at 8:49then()
tomap()
, you just can chainthen()
to a function that returns a promise – Oriol Grau Commented Oct 10, 2019 at 8:50cars
array already, then you don't need a connection, so you can simply terminate before the.map
call and nothing should change. Or you can callcars.map(/* ... */); connection.end();
which is guaranteed to run after the mapping operation. – VLAZ Commented Oct 10, 2019 at 8:53