サーバレス練習帳

着眼大局着手小局

fetchi

https://www.webdesignleaves.com/pr/jquery/fetch-api-basic.html


何パターンかの書き方を覚えておこう。
返り値せあるPromiseにも書けるし・・・

//fetch() は Promise を返す(返り値を変数に代入する場合)
const promise = fetch('https://jsonplaceholder.typicode.com/users');

//fetch() のレスポンス(リクエストの結果)を then() メソッドで処理
promise.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});

こんな書き方もあるし・・・

fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});


このようにも書けるし、

fetch('https://jsonplaceholder.typicode.com/users')
.then( response => response.json() )
.then( data => console.log(data) );

アロー関数をfunction()で書いても良いし、

fetch('https://jsonplaceholder.typicode.com/users')
.then( function (response) {
return response.json();
})
.then( function(data) {
console.log(data);
}

他にも、単純にawaitで待っても良いし、色々ある。

なんか非同期処理の書き方がわかってきた気がする。

PromiseとThenについては、こちらを見た。