JavaScript |从另一个承诺访问承诺的对象



在我的AngularJS应用程序中,我想访问Promise的返回值,我从控制器外部的服务访问该值并将其导入到那里。此承诺,返回一个对象。我想访问其中的对象和属性。

我创建了服务来获取该终结点。看下面:

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..
  }

实际结果现在,在我的控制台中,我得到了checkIfItAvailable打印出来的功能。

预期成果相反,我想将原始承诺、对象及其属性返回的实际值打印到控制台。

可能需要调用该函数,而不仅仅是将其作为参数传递。

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

在这里,getEndpoints是一个返回 Promise 的异步函数,从 promise 获取返回值的方法是使用then回调。你可以这样做:

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

调用getEndpoints()和使用then() function checkIfItIsAvailable访问getEndpoints的解析结果:

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

最新更新