teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

fetchを使う方向で、いただいたコードとともに挙動の確認をしたので追記にまとめました。

2021/09/29 02:07

投稿

fungi
fungi

スコア2

title CHANGED
File without changes
body CHANGED
@@ -73,7 +73,83 @@
73
73
  length:0
74
74
  と出力されてしまいました。
75
75
 
76
+ ##追記
76
77
 
78
+ 昨日fetchの方が適しているとのご意見をいただき、調べながら確認したことをまとめます。
79
+ ご教示いただいた下記コードですが、
80
+
81
+ const getCSV=()=>fetch('sample.csv').then(res=>res.text()).then(csvArray);
82
+ const csvArray=str=>str.split("\r\n").map(x=>x.split(","));
83
+
84
+ (async ()=>{
85
+ const result=await getCSV();
86
+ console.log(result); ※1
87
+ })();
88
+
89
+ //↑この外でresultを参照できませんでした。
90
+
91
+ console.log(result) //Uncaught・・・
92
+
93
+ //※1では
94
+ //(5) [Array(2), Array(2), Array(2), Array(2), Array(2)]
95
+ //0: (2) ['"0001"', '11']
96
+ //1: (2) ['"0002"', '12']
97
+ //2: (2) ['"0003"', '13']
98
+ //3: (2) ['"0004"', '14']
99
+ //のように出力され、配列になっていました。
100
+
101
+ //そこで、resultを最初に定義してみましたが、
102
+
103
+ let result = []
104
+
105
+ const getCSV=()=>fetch('sample.csv').then(res=>res.text()).then(csvArray);
106
+ const csvArray=str=>str.split("\r\n").map(x=>x.split(","));
107
+
108
+ (async ()=>{
109
+ result=await getCSV();
110
+ console.log(result);
111
+ })();
112
+
113
+ console.log(result)
114
+
115
+ //以下のような出力結果になりました。
116
+ //[]
117
+ // length: 0
118
+ // [[Prototype]]: Array(0)
119
+ //(5) [Array(2), Array(2), Array(2), Array(2), Array(2)]
120
+ // 0: (2) ['"0001"', '11']
121
+ // 1: (2) ['"0002"', '12']
122
+ // 2: (2) ['"0003"', '13']
123
+ // 3: (2) ['"0004"', '14']
124
+
125
+ resultの中身が空のままになってしまいました。
126
+ resultを配列として別の関数で参照したり、result[1]などのように扱いたいので
127
+ グローバル変数としたいと思っています。
128
+ 自分でも調べながらやってみたのですが、
129
+
130
+ let result = fetch("sample.csv").then(res=>res.text()).then(function convertCSVtoArray(str){
131
+ const temp = str.split("\r\n")
132
+ for(let i=0;i<temp.length;++i){
133
+ result[i] =temp[i].split(",")
134
+ }
135
+ })
136
+
137
+ console.log(result)
138
+
139
+ //↑のようにすると、以下のように出力されます。
140
+
141
+ //Promise {<pending>}
142
+ //0: (2) ['"0001"', '11']
143
+ //1: (2) ['"0002"', '12']
144
+ //2: (2) ['"0003"', '13']
145
+ //3: (2) ['"0004"', '14']
146
+
147
+ Promiseの概念がつかめていないままなのですが、
148
+ pendingとなっているということは、値は検出してるけど、
149
+ まだresultに取得できていないということでしょうか?
150
+
151
+
152
+
77
153
  ### 補足情報(FW/ツールのバージョンなど)
78
154
 
79
155
  ここにより詳細な情報を記載してください。