Await delay(1000) - error in array

Hi,
I try to use await delay(1000) into this function

const delay = ms => new Promise(res => context.set("timer", setTimeout(res, ms)));

//x is an array
const x = msg.payload;

x.forEach(element => {
    const valore = (element.value)
    const id = (element.id)
    msg.topic = "UPDATE Variables SET Valore = '" + valore + "' WHERE Id = " + id
    msg.pass = 2
    node.status(valore + " " + id)
    node.send(msg)

    await delay(1000);
}
);

but I have this error:

How can I fix it?

Have you tried the "quick fix" (hint, the arrow function must be async - just like the tip says)

That said...

This is NOT the node-red / low-code way. Get rid of the async await & simply send all your messages out of the function without delay then pass the msg through a delay node set to rate limit 1 msg per sec.

2 Likes

And better still, create a more efficient SQL update statement that does it all in 1 statement.

3 Likes

Yes,
I tried the "quick fix" and the function works but without delay ......

It's what I did until today, then I thought this method was better (have a break before instead after) .....

You're right, but this is the better that I can do ....

Ah ok, yes. You cannot delay an array forEach. You would need to use a regular for loop

What @TotallyInformation says is a single statement.

Instead of looping one by one, create a single string with all the update statements and then execute it. This is extremely fast.

eg.

const input = msg.payload;
const output = ""

input.forEach(el => {
    output += `UPDATE Variables SET Valore = '${el.value}' WHERE Id = ${el.id};`
})

msg.topic = output
return msg

Thank you so much!

Note that if your SQL DB supports them, prepared statements are typically FAR more efficient, especially for repeated updates and inserts.