0

I am using the times() method of async.js (https://caolan.github.io/async/docs.html#times).

It basically calls an async function X amount of times, and then once every async function resolves, it gives you the opportunity to consolidate your results in one callback.

I notice when I mimic a 404 or any error, I can pass the error to the final callback and either render a visual prompt to the user, log it to the server, etc.

Whenever I force an error, I always get an error in my console also:

Uncaught (in promise) Error: Unexpected status code [404] on URL...

Am I doing something wrong in terms of handling this error (Should I actually not being seeing this if I was handling the error correctly)?

My async function, and then my times() implementation basically looks like:

var getPrismicStories = function(pageNumber, callback) {
  let stories = [];

  Prismic.api("https://myendpoint.prismic.io/api",{accessToken}).then((api) => {
        return api.query(Prismic.Predicates.any('document.type', ['blog-posts','video-posts']),{pageSize : 100, page : pageNumber, orderings : '[document.first_publication_date desc]',after:lastInitialStoryId})
  }).then((prismicResponse) => {
    stories = prismicResponse.results;
    callback(null, stories);
  }).catch((error) => {callback(error,stories)});
};

times(4, (i,next) => {
  getPrismicStories(++i, function(err, stories) {
    next(err, stories);
  });
}, function(err, allStories) {
  if(err){
    console.error(err);
  }

  doSomethingWithFetchResults(allStories);
});

I am forcing the 404 for instance, by requesting an incorrect URL name ("notmyendpoint.prismic.io/api").

connected_user
  • 814
  • 1
  • 9
  • 25
  • @Xufox it has been posted. – connected_user Apr 25 '18 at 19:33
  • Do not use async.js with promises. – Bergi Apr 25 '18 at 20:03
  • You will want to [use `.then(…, …)` instead of `.then(…).catch(…)`](https://stackoverflow.com/q/24662289/1048572) – Bergi Apr 25 '18 at 20:04
  • @Bergi, Why shouldn't I use promises, and what is the difference in the comparison in your comment? – connected_user Apr 25 '18 at 20:11
  • @Bergi Also, do these recommendations pertain to my original problem in any way? – connected_user Apr 25 '18 at 20:12
  • I said you should not use async.js, not that you should not use promises :-) The difference between the two snippets is explained in detail in the linked answer. And yes, if `callback` throws (which is quite likely given that you call `doSomethingWithFetchResults` even when there was an error), this might be the reason for your problem. – Bergi Apr 25 '18 at 20:15
  • @Bergi Why should I not use async.js :O – connected_user Apr 25 '18 at 20:20
  • Because promises are superior to callbacks, and mixing them doesn't work well (as you experienced). `times` is really trivial to write yourself with promises if you want. – Bergi Apr 25 '18 at 20:25

0 Answers0