maudulus
maudulus

Reputation: 11045

Using Promise, getting error "Cannot read property 'then' of undefined"

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?

Upvotes: 1

Views: 1917

Answers (2)

Jerome
Jerome

Reputation: 131

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');
});

Upvotes: 1

Mike Cluck
Mike Cluck

Reputation: 32521

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');
});

Upvotes: 2

Related Questions