請問這個寫法還有什麼問題嗎??
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));
}
你好,那個 getGuest
跟 showGuestAndMessage
的寫法可以再簡化一點,可以用 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);
}