如何将已解析的promise对象检索为外部作用域中的变量?

时间:2016-10-27 12:30:00

标签: scope ecmascript-6 es6-promise

我正在尝试从名为getByUsername()的函数返回一个对象。正确的对象出现在then()块中。我无法从返回undefined的外部函数返回该对象。

const url = 'https://jsonplaceholder.typicode.com/users/';

function get(url) {
  return fetch(url)
    .then(response => response.json());
}

const users = get(url)
  .then(users => users);

function getByUsername(x) {
  return users.then((user) => {
    return user.find((user) => {
      return user.username === x;
    });
  })
    .then((user) => {
      console.log(user); // Correct object
      return user;
    });
}

getByUsername('Kamren');

1 个答案:

答案 0 :(得分:2)

getByUsername()返回一个承诺。您无法立即访问该值,只能在then()回调中使用

getByUsername('Kamren').then(user => console.log(user))

或者,如果您使用的是Babel,则可以使用transform-async-to-generator插件并使用异步功能:

;(async () => {
  const user = await getByUsername('Kamren')
  console.log(user)
})()