1

I'm using promise and was following another example, but when I run the script I am getting an error TypeError: Cannot read property 'then' of undefined. My code appears as the following:

var completedLinks = ["http://www.example.com/1","http://www.example.com/2","http://www.example.com/3"]
function fetchSiteDetails(arr){
  arr.reduce(function(promise, email) {
    console.log(email)
  }, Promise.resolve());
}

fetchSiteDetails(completedLinks).then(function() {
    console.log('all done');
});

I guess that fetchSiteDetails isn't valid to use then on, but I'm not sure why?

Community
  • 1
  • 1
maudulus
  • 10,627
  • 10
  • 78
  • 117

2 Answers2

2

You aren't returning a promise from fetchSiteDetails, nor are you producing a value with arr.reduce. Try something like this:

function log(message) {
  document.body.innerHTML += message + '<br />';
}

function fetchSiteDetails(arr) {
  return arr.reduce(function(promise, email) {
    log(email);
    return promise;
  }, Promise.resolve());
}

fetchSiteDetails([1, 2, 3]).then(function() {
  log('Done');
});
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
  • @charlietfl The then will work as the initial value is a promise and it is not changed in any way through the reduce, which WILL return a promise, but the function still does nothing useful. – ryan0319 Jan 28 '16 at 22:37
  • If I add something inside, such as a request to cheerio, will it wait to complete that job before starting on the next link? – maudulus Jan 28 '16 at 22:37
  • @maudulus No because you're using `.reduce` which runs synchronously. Instead, you'd likely have to setup a series of promises which only resolve the one you're returning after all of the other ones have completed. – Mike Cluck Jan 28 '16 at 22:40
1

It's like you want the same behavior that Promise.all() already provides. Try something like this:

var completedLinks = ["http://www.example.com/1","http://www.example.com/2","http://www.example.com/3"]
function fetchSiteDetails(arr){
  return Promise.all(arr.map(function(email) {
    return Promise.resolve(); // do whatever here, but return a promise !
  }));
}

fetchSiteDetails(completedLinks).then(function() {
  console.log('all done');
});
Jerome
  • 131
  • 6