JavaScript的|从另一个无极访问无极的对象

问题描述 投票:1回答:3

在我的AngularJS应用,我想访问一个承诺,这是我从一个服务访问我的控制器之外并将其导入那里的返回值。这个承诺,返回一个对象。我想访问该对象和它里面的属性。

我创建的服务来获取该端点。往下看:

export const getEndpoints = () => {
  const options = {
    method: httpMethod.GET,
    url: endpoint.ENVIRONMENT,
  };
  return Instance(options);
};

作为回报,上述服务将读取的终点,我提供和使用axios的背景。这部分工作得很好。

然后导入它,在我的角度控制器:

import { getEndpoints } from './config/service';

最后我创造了这个功能:

$scope.isItAvailable = false; // I will use this later to check the actual value. It is not important in the scope of the question..

  const checkIfItIsAvailable = () => {
    return new Promise((resolve, reject) => {
      resolve(getEndpoints)
      console.log(getEndpoints)
    })
  }

  // And in my main function I am just calling the above
  const mainFn = () => {
    checkIfItIsAvailable()
    // Along with a few others..
  }

实际结果现在,在我的控制台,我得到打印出来的functioncheckIfItAvailable

预期结果我反而想打印到控制台,即由当初的诺言,对象和它的属性返回的实际值。

javascript angularjs object redux es6-promise
3个回答
1
投票

也许你需要调用该函数,而不是仅仅把它当作一个参数。

const checkIfItIsAvailable = () => {
    return new Promise((resolve, reject) => {
      resolve(getEndpoints()) // here
      console.log(getEndpoints())
    })
  }

然后让在你的主要功能以后解决,或任何地方 - 只是使用then

const mainFn = () => {
    checkIfItIsAvailable().then((result) => {
       // do what you need with result here
       // $scope.isItAvailable = result   probably like this
    });
}

如果你需要其他的结果,请发表评论。我看到至少在目前这个问题。

此外,这里是一个剪断,说明你需要,而不是把它的只是路过。

// here is an example function which just return some string
function getSomething() {
  return 'something'; // it could be a promise also
}

// here is example without calling functions, but just passing:
const promise = new Promise((resolve, reject) => {
  console.log('NO CALL: ', getSomething);
});

// here is example with calling, so value is resolved
const promise2 = new Promise((resolve, reject) => {
  console.log('CALLED: ', getSomething());
});

0
投票

在这里,getEndpoints是一个异步函数返回一个承诺,并得到承诺返回值的方法是使用then回调。你可以像下面这样做:

const checkIfItIsAvailable = () => {
    return new Promise((resolve, reject) => {
      getEndpoints().then(resultOfEndPoint => {
        console.log(resultOfEndPoint);
        resolve(resultOfEndPoint);
      });
    })
  }

-1
投票

它可以访问getEndpoints的解决结果checkIfItIsAvailable调用getEndpoints()和使用then() function

const checkIfItIsAvailable = () => {
  return new Promise((resolve, reject) => {
    // call getEndpoints
    getEndpoints()
      // call then to get a result from getEndpoints
      .then(res => {
        console.log(res);
        // checkIfItIsAvailable will be resolved with
        // the result of getEndpoints
        resolve(res);
      });
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.