質問
jsで複数の関数でfetchを使い、getやpostをしています。
サンプルコードでは、getの関数getAllId()、putの関数execution()、それらの関数を実行している関数init()に分けています。
今の書き方だと、init() の中のthen()などが入れ子になりすぎて可読性に欠けると思っています。
このようなことをしたい場合、どのように書くべきなのか教えて頂きたいです。
js
javascript
class Api { constructor(_parm) { // APIトークン(仮。実際はenvなどに記載する想定です) this.apiToken = 'xxxxxxxxxxxxxxxx'; } async getAllId() { const url = 'https://xxxxxxxxxxxxx'; const options = { method: 'GET', headers: { Accept: 'application/json', 'x-chatworktoken': this.apiToken } }; const response = await fetch(url, options); return response.json(); } async execution(_id) { const url = `https://xxxxxxxxxxxxx/${_id}`; const options = { method: 'PUT', headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'x-chatworktoken': this.apiToken } }; const response = await fetch(url, options); return response.json(); } init() { this.getAllId() .then(_datas => { const arrayIds = _datas.map(_data => _data.id); arrayIds.forEach(_id => { this.execution(_id) .then(_res => { console.log(_res); }) .catch((error) => { console.error('Error:', error); }); ; }); }) .catch((error) => { console.error('Error:', error); }); }} const api = new Api();api.init();

0 コメント