0

I have a little problem, I need the makeZip function to wait for the takeScreenshot function to take all the screenshots it needs, how do I do this while taking care of best practices? (I know at this point "then" doesn't make sense with the post method, I just tried it my way before but it didn't work the way I wanted)

Function:

const takeScreenshot = (url) => {
  const resolutionsArray = Object.values(resolutions);
  resolutionsArray.map(async (mediaSize) => {
    webshot(url, setFileName(url, mediaSize), setOptions(mediaSize), (err) => {
      if (!err) {
        console.log("screenshot taken!");
      }
    });
  });
};

calling functions:

app.post("/", async (req, res) => {
  const { url } = req.body;
  takeScreenshot(url)
    .then((url) => makeZip(url))
    .then((url) => sendEmail(url))
    .then((message) => res.send(message))
    .catch((err) => console.log(err));
});

2 Answers 2

2

My suggestion is:

  1. to use Promise.all or Promise.allSettled when you need to handle several promises
  2. extract callback of map fn
const makeWebshot = (argsHere) => new Promise((reselove, reject) => {
  webshot(url, setFileName(url, mediaSize), setOptions(mediaSize), (err) => {
      if (err) return reject(err);
      return resolve();
    });
});
  1. Update takeScreenshot to
const takeScreenshot = (url) => {
  const resolutionsArray = Object.values(resolutions);
  return Promise.all(resolutionsArray.map((mediaSize) => makeWebshot(argsHere)));
};
Sign up to request clarification or add additional context in comments.

Comments

0

When dealing with a list of Promises you will want to use Promise.all to wait for them all to resolve. Here is a simple example:

const list = [1,2,3];
const all = list.map(i => new Promise((resolve, reject) => {
  setTimeout(() => { 
    console.log(i);
    resolve(i*2);
  }, 100);
}));
Promise.all(all).then(console.log)

In your case it would be something like this:

const takeScreenshot = (url) => 
  Object.values(resolutions).map(async (mediaSize) => {
    webshot(url, setFileName(url, mediaSize), setOptions(mediaSize), (err) => {
      if (!err) {
        console.log("screenshot taken!");
      }
    });
  });

app.post("/", async (req, res) => {
  const { url } = req.body;
  Promise.all(takeScreenshot(url))
    .then((listOfUrls) => ...
});

But since I don't know what webshot returns, I can't tell you what the processing of the listOfUrls should look like.

1 Comment

sadly its void function, thats a problem. Its just making jpg's in a folder

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.