소개
게시글
고민있어요
[참고] 공공데이터포털 데이터도 9월부터는 사용할 수 없습니다.
- 1
- 0
- 219
질문&답변
생성자에서 비동기처리
interface PhoneNumberDictionary { [phone: string]: { num: number }; } interface Contact { name: string; address: string; phones: PhoneNumberDictionary; } enum PhoneType { Home = 'home', Office = 'office', Studio = 'studio', } // api function fetchContacts(): Promise> { const contacts: Array = [ { name: 'Tony', address: 'Malibu', phones: { home: { num: 11122223333 }, office: { num: 44455556666 }, }, }, { name: 'Banner', address: 'New York', phones: { home: { num: 77788889999 }, }, }, { name: '마동석', address: '서울시 강남구', phones: { home: { num: 213423452 }, studio: { num: 314882045 }, }, }, ]; return new Promise(resolve => { setTimeout(() => resolve(contacts), 2000); }); } // main class AddressBook { contacts: Array; constructor() { this.contacts = []; // this.fetchData(); } async fetchData(): Promise { // fetchContacts().then(res => { // this.contacts = res; // }); const res = await fetchContacts(); this.contacts = res; } findContactByName(name: string): Array { return this.contacts.filter(contact => contact.name === name); } findContactByAddress(address: string): Array { return this.contacts.filter(contact => contact.address === address); } findContactByPhone( phoneNumber: number, phoneType: PhoneType ): Array { return this.contacts.filter( contact => contact.phones[phoneType].num === phoneNumber ); } addContact(contact: Contact): void { this.contacts.push(contact); } displayListByName(): Array { return this.contacts.map(contact => contact.name); } displayListByAddress(): Array { return this.contacts.map(contact => contact.address); } } (async (): Promise => { console.log('Wait for 2 seconds..'); const addressBook = new AddressBook(); await addressBook.fetchData(); return addressBook; })().then(addressBook => { console.log(addressBook); console.log(addressBook.findContactByName('마동석')); console.log(addressBook.findContactByAddress('Malibu')); console.log(addressBook.findContactByPhone(77788889999, PhoneType.Home)); console.log(addressBook.displayListByName()); console.log(addressBook.displayListByAddress()); console.log('================================================='); addressBook.addContact({ name: 'Haguri', address: 'Jeonbuk', phones: { home: { num: 1011119999 }, office: { num: 6312345678 }, }, }); console.log(addressBook.contacts); });위 코드는 제가 작성하고 테스트 해본 코드이구요. 참조 링크는 아래와 같습니다.https://stackoverflow.com/questions/36363278/can-async-await-be-used-in-constructors
- 1
- 3
- 956
고민있어요
(정보) 날짜 formatting
- 0
- 0
- 184