0

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

ali
  • 55
  • 1
  • 6

1 Answers1

0

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...
        });
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875