Cannot read property 'then' of undefined with JavaScript promises

筅森魡賤 提交于 2019-12-10 09:40:34

问题


I understand at first glance this may look like a duplicate but I have seen all the answers for that tell me to put a return in but that is not working.

this is my function:

function removePastUsersFromArray(){
  pullAllUsersFromDB().then(function(users_array){
  var cookie_value = document.cookie.split('=') [1];
  const promises = []
    for (var i = 0; i < _USERS.length; i++) {
      if (_USERS[i].useruid == cookie_value){
      var logged_in_user = _USERS[i].useruid;
        promises.push(
          onChildValue(rootRef, 'users/' + logged_in_user + '/disliked_users/').then(formatUsers)
        )
        promises.push(
          onChildValue(rootRef, 'users/' + logged_in_user + '/liked_users/').then(formatUsers)
        )
      }
    }
    return Promise.all(promises);
  })
};

and I get the error at this function:

function displayRemovedPastUsersFromArray(){
  removePastUsersFromArray().then(function(promises){

basically saying that my removePastUsersFromArray is undefined. but it isn't as it clearly exists above and returns promises??


回答1:


basically saying that my removePastUsersFromArray is undefined

No, it says that the removePastUsersFromArray() call returned undefined, as that's what you're trying to call then upon.

it clearly exists above and returns promises?

It exists, yes, but it doesn't return anything. The return you have is inside the then callback, but the function itself does not have a return statement. return the promise that results from the chaining:

function removePastUsersFromArray() {
  return pullAllUsersFromDB().then(function(users_array) {
//^^^^^^
    var cookie_value = document.cookie.split('=') [1];
    const promises = []
    for (var i = 0; i < _USERS.length; i++) {
      if (_USERS[i].useruid == cookie_value){
        var logged_in_user = _USERS[i].useruid;
        promises.push(
          onChildValue(rootRef, 'users/' + logged_in_user + '/disliked_users/').then(formatUsers)
        );
        promises.push(
          onChildValue(rootRef, 'users/' + logged_in_user + '/liked_users/').then(formatUsers)
        );
      }
    }
    return Promise.all(promises);
  })
};


来源:https://stackoverflow.com/questions/39509589/cannot-read-property-then-of-undefined-with-javascript-promises

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!