如何将这个异步函数转换为 Promise?

问题描述 投票:0回答:2

你好,我有这个异步函数,它通过 github api 检索用户配置文件和存储库,并将它们返回到一个对象中。

我想通过使用承诺链(没有任何辅助方法)将其转换为基于承诺的函数。

async function getUser(user) {
  const profileResponse = await fetch(`https://api.github.com/users/${user}`);
  const profileData = await profileResponse.json();

  const repoResponse = await fetch(`https://api.github.com/users/${user}/repos`);
  const reposData = await repoResponse.json();
  // returning an object with profile and data
  return {
    profile:profileData,
    repos:repoData,
  };
}

//Calling the function here.
getUser("abufattah").then((res) => console.log(res));

我已经设法使用两个辅助函数和 Promise.all() 方法来完成它。

但是我如何通过使用承诺链而不使用任何辅助函数来实现同样的事情。

//Helper function 1: returns a promise with user profile data.
function getUserProfile(user) {
  return fetch(`https://api.github.com/users/${user}`)
         .then((res) =>res.json());
}


//Helper function 2: returns a promise with user repositories data.
function getUserRepos(user) {
  return fetch(`https://api.github.com/users/${user}/repos?per_page=5&sort=created`)
         .then((res) => res.json());
}
//Main function
function getUserWithPromise(user) {
  return new Promise((resolve) => {
    let profile = getUserProfile(user);
    let repos = getUserRepos(user);

    Promise.all([profile, repos]).then((values) => {
      resolve({ profile: values[0], repos: values[1] });
    });
  });
}

// calling the function here
getUserWithPromise("abufattah").then((res) => console.log(res));
javascript async-await es6-promise
2个回答
4
投票

async
/
await
语法转换为
.then()
调用非常机械,特别是如果它不涉及任何控制流语法(循环或条件):

function getUser(user) {
  return fetch(`https://api.github.com/users/${user}`).then(profileResponse => {
    return profileResponse.json().then(profileData => {
      return fetch(`https://api.github.com/users/${user}/repos`).then(repoResponse => {
        return repoResponse.json().then(reposData => {
          // returning an object with profile and data
          return {
            profile:profileData,
            repos:reposData,
          };
        });
      });
    });
  });
}

但是没有充分的理由编写这样的代码。如果只是您的目标环境不支持

async
/
await
,请让转译器进行转换。


3
投票

您可以:

//Main function
function getUserWithPromise(user) {
  return Promise.all([
    fetch(`https://api.github.com/users/${user}`).then((res) =>res.json()),
    fetch(`https://api.github.com/users/${user}/repos?per_page=5&sort=created`).then((res) => res.json())
  ]).then(([result1, result2]) => ({ profile: result1, repos: result2 }));
}

// calling the function here
getUserWithPromise("abufattah").then((res) => console.log(res));

链条:

function getUserWithPromise(user) {
  return fetch(`https://api.github.com/users/${user}`)
    .then((res) => {
      return fetch(`https://api.github.com/users/${user}/repos?per_page=5&sort=created`).then((fetch2Result) => ([res.json(), fetch2Result.json()]))
    }).then(([result1, result2]) => ({ profile: result1, repos: result2 }))
}

// calling the function here
getUserWithPromise("abufattah").then((res) => console.log(res));
© www.soinside.com 2019 - 2024. All rights reserved.