Why does the Node.js event listener "pause" the execution of an async function to start second execution if to emit the same event second time? And the second question: how does it possible to finish first execution, then start the second one?
I.e., if to launch this code in Node.js:
import { EventEmitter } from "events";
let event = new EventEmitter();
event.on("myEvent", async function () {
console.log("Start");
await new Promise((resolve, reject) => {
setTimeout(() => {
resolve(console.log("Do job"));
}, 1000);
});
console.log("Finish");
});
event.emit("myEvent"); // first emit
event.emit("myEvent"); // second emit
Then I'm getting such result:
Start
Start
Do job
Finish
Do job
Finish
Hovewer I'd like to see this:
Start
Do job
Finish
Start
Do job
Finish
UPDATE Below I put real code which contains the described problem
const web3 = new Web3(
new Web3.providers.WebsocketProvider(
"wss://eth-mainnet.g.alchemy.com/v2/<API-KEY>"
)
);
let walletAddress = "0x123";
let options = {
topics: [web3.utils.sha3("Transfer(address,address,uint256)")],
};
let subscription = web3.eth.subscribe("logs", options);
subscription.on("data", async (event) => {
if (event.topics.length == 3) {
let transaction = decodeTransaction(event); //just using web3.eth.abi.decodeLog(...)
if (
transaction.from === walletAddress ||
transaction.to === walletAddress
) {
const contract = new web3.eth.Contract(abi, event.address);
let coinSymbol = await contract.methods.symbol().call(); //<-- The issue starts here
await redisClient.hSet(
walletAddress,
coinSymbol,
transaction.value
);
}
}
});