Array.prototype.find() 在异步函数中返回 undefined

Ale*_*xar 3 javascript asynchronous http promise angularjs

我的Array.prototype.find()方法有问题。它在使用时似乎无法正常工作$http request..我已经尝试了所有想到的方法,但它总是返回未定义。我猜的错误是存在的,因为我登录response.datauser_to_find定义之前found_user,并预期其价值。

所以我有这个服务:

app.service('UserService', ['$http','$q', function($http, $q) {
  return {
    findUser: function(user_to_find) {
      let defer = $q.defer();
      $http({
        method: "GET",
        url: 'http://localhost:3000/users'
      }).then(function(response){
        let found_user = response.data.find(acc=>{ //found_user is always undefined
          acc.username == user_to_find;
        })
        defer.resolve(found_user);
      }),function(response) {
        defer.reject(response);
        console.log("Error finding user");
      }
      return defer.promise;
    }
  }
}])
Run Code Online (Sandbox Code Playgroud)

lip*_*ipp 11

你缺少一个return. 谓词(传递给 find 的函数)在您的情况下返回 undefined,因此 find 算法不会获得“匹配”。

只需添加return

    let found_user = response.data.find(acc=>{ //found_user is always undefined
      return acc.username == user_to_find;
    })
Run Code Online (Sandbox Code Playgroud)

如果您不使用花括号,则可以省略它

    let found_user = response.data.find(acc=> ( //found_user is always undefined
      acc.username === user_to_find;
    ))
Run Code Online (Sandbox Code Playgroud)

我还建议使用===(严格比较)而不是==进行比较。

  • 不客气!别担心,每个人都不止一次遇到过类似的问题:) (2认同)