0

I have my function getting an email from Gmail. I want to run this function n times or until an email is found.

What is a proper way to do it? I tried: http://caolan.github.io/async/docs.html#retry but without success.

I was following this article how to read emails: https://developers.google.com/gmail/api/quickstart/nodejs

nvldk
  • 125
  • 2
  • 14

1 Answers1

1

Assuming you have a routine called gmail, which returns a promise which succeeds (fulfills) if an email is found, and otherwise fails (rejects), then:

function get(n) {
  return gmail().catch(() => {
    if (!n) throw "Too many tries!";
    return get(--n);
   };
}

Usage:

get(5).then(
  mail => console.log(mail.body),
  () => console.log("No mail!"));

If for some reason you do not like the recursive style:

function get(n) {
  let promise = Promise.reject();

  do { promise = promise.catch(gmail); } while (n--);

  return promise;
}

If gmail is callback style, then

function get(n, cb) {
  gmail(function(err, data) {
    if (err) 
      if (!n) get(--n, cb); 
      else cb("Too many tries!");
    else cb(null, data);
  });
}

Or better yet, promisify gmail, either using a library or

function promisify(fn) {
  return new Promise((resolve, reject) {
    fn(function(data, err) {
      if (err) reject(err);
      else resolve(data);
    });
  });
}

and then replace gmail in the first solution with promisify(gmail).

  • unfortunately my function does not return a promise. I guess recursion is the way to go? – nvldk Dec 17 '16 at 18:11
  • @dzvert use the solution above, but use the callback, or wrap the API as a function that returns a promise ([link](http://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises)) – samsonthehero Dec 18 '16 at 06:14
  • @samsonthehero I've already tried that but getting "then is not a function" error. – nvldk Dec 18 '16 at 10:24