首页 > 解决方案 > 承诺不交回报

问题描述

class UserStorage {
  async loginUser(id, pw) {
    await setTimeout(() => {
      if (
        (id === "ellie" && pw === "dream") ||
        (id === "coder" && pw === "academy")
      )
        return id;
      else return new Error("not found user info");
    }, 1000);
  }
  async getRoles(user) {
    if (user === "ellie") return { name: "ellie", role: "admin" };
    else return new Error("no access");
  }
}
const userStorage = new UserStorage();

const id = prompt("wowSans");
const password = prompt("pw");

userStorage
  .loginUser(id,password)
  .then(userStorage.getRoles)
  .then((value) => console.log(`Hi ${value.name}! Your Role is ${value.role}!`))
  .catch(console.log);

我要打印“嗨,艾莉!您的角色是管理员!” 但它不起作用。它打印“嗨,错误!您的角色未定义!” 我今天第一次遇到 Promise 和 async/await。有人知道合适的解决方案吗?请回答!

标签: javascript

解决方案


推荐阅读