iT邦幫忙

0

promise async await

  • 分享至 

  • xImage

請問這個寫法還有什麼問題嗎??

function getUser(userId: number): Promise<{ name: string }> {
  return Promise.resolve({ name: "User" });
}

function getMessage(): Promise<{ name: string }> {
  return Promise.resolve({ name: "hello" });
}

async function getGuest(): Promise<{ name: string }> { 
  let onResolve: ({ name: string }) => void = null;
  const answer = new Promise<{ name: string }>(resolve => onResolve = resolve);
  getUser(2).then(user => onResolve(user));
  return answer;
}

async function showGuestAndMessage(): void {
  task().then(user => console.log(user.name))
    .then(() => getMessage())
    .then(message => console.log(message.name));
}
不知道,或許你跑看看有沒有什麼問題。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
HAO
iT邦研究生 1 級 ‧ 2022-03-29 09:21:17

你好,那個 getGuestshowGuestAndMessage 的寫法可以再簡化一點,可以用 async/await 來扁平化,然後我不知道 task 是不是打錯了,我猜應該是 getUser 或是 getGuest

function getUser(userId: number) {
  return Promise.resolve({ name: "User" });
}

function getMessage() {
  return Promise.resolve({ name: "hello" });
}

function getGuest() { 
  return getUser(2);
}

async function showGuestAndMessage() {
  const guest = await getGuest();
  console.log(guest.name);
  const message = await getMessage();
  console.log(message.name);
}

我要發表回答

立即登入回答