Home > Enterprise >  Nodejs: listen to array in express
Nodejs: listen to array in express

Time:12-06

This is my code:

let newArray = []
const myProcess = (id) => {
  // after 5 seconds, add id to newArray
}

router.use('/', async (req, res) => {
  myProcess(req.query.id);
  if (newArray.includes(req.query.id) {
    res.send({})
  }
}

But this code not work for me

I want to send {} after add id to newArray

CodePudding user response:

To fix this, you can use the await keyword to wait for the myProcess function to finish before checking if the newArray array includes the id. example;

let newArray = []
const myProcess = (id) => {
  // after 5 seconds, add id to newArray
  setTimeout(() => {
    newArray.push(id)
  }, 5000)
}

router.use('/', async (req, res) => {
  await myProcess(req.query.id);
  if (newArray.includes(req.query.id) {
    res.send({})
  }
}

CodePudding user response:

You've said:

  • myProcess will add an ID to the array after five seconds
  • you don't want to send the {} until the ID has been added

That means that your code won't respond to the request for / for five seconds, which is a long time in "I'm waiting for something" terms. :-) Just to flag that up.

But to do it, have myProcess return a promise it fulfills once it's added the ID to the array, then wait for that promise to settle before sending the response:

let newArray = [];
const myProcess = (id) => {
    return new Promise((resolve, reject) => {
        // after 5 seconds, add id to newArray and call
        // `resolve` (or call `reject` if something
        // goes wrong)
    });
};

router.use("/", async (req, res) => {
    myProcess(req.query.id)
        .then(() => {
            if (newArray.includes(req.query.id)) {
                res.send({});
            } else {
                // ...send something else...
            }
        })
        .catch((error) => {
            // ...send an error reply...
        });
});
  • Related