質問
jsで複数の関数でfetch
を使い、getやpostをしています。
サンプルコードでは、getの関数getAllId()
、putの関数execution()
、それらの関数を実行している関数init()
に分けています。
今の書き方だと、init()
の中のthen()
などが入れ子になりすぎて可読性に欠けると思っています。
このようなことをしたい場合、どのように書くべきなのか教えて頂きたいです。
js
javascript
1class Api { 2 constructor(_parm) { 3 // APIトークン(仮。実際はenvなどに記載する想定です) 4 this.apiToken = 'xxxxxxxxxxxxxxxx'; 5 } 6 7 /** 8 * 全てのIDを取得(GETメソッド) 9 * {[id: 1, hoge: xxx], [id: 2, hoge: yyy]}のようなデータが返ってくる想定 10 * @returns Array 全てのID 11 */ 12 async getAllId() { 13 const url = 'https://xxxxxxxxxxxxx'; 14 const options = { 15 method: 'GET', 16 headers: { 17 Accept: 'application/json', 18 'x-chatworktoken': this.apiToken 19 } 20 }; 21 const response = await fetch(url, options); 22 return response.json(); 23 } 24 25 /** 26 * IDを元に何かを実行(PUTメソッド) 27 */ 28 async execution(_id) { 29 const url = `https://xxxxxxxxxxxxx/${_id}`; 30 const options = { 31 method: 'PUT', 32 headers: { 33 Accept: 'application/json', 34 'Content-Type': 'application/x-www-form-urlencoded', 35 'x-chatworktoken': this.apiToken 36 } 37 }; 38 const response = await fetch(url, options); 39 return response.json(); 40 } 41 42 init() { 43 this.getAllId() 44 .then(_datas => { 45 const arrayIds = _datas.map(_data => _data.id); 46 arrayIds.forEach(_id => { 47 this.execution(_id) 48 .then(_res => { 49 console.log(_res); 50 }) 51 .catch((error) => { 52 console.error('Error:', error); 53 }); 54 ; 55 }); 56 }) 57 .catch((error) => { 58 console.error('Error:', error); 59 }); 60 } 61} 62 63const api = new Api(); 64api.init();
init() で async/await を使わないのは何か理由があるのでしょうか。

回答2件
あなたの回答
tips
プレビュー