Fetch APIおよびPromiseを使用してRestfulインタフェースをPOSTに呼び出す


Basic Concept
Promise
Overview
  • Promise is a js standard built-in object.
  • Promise is used for asynchronous computations.
  • A Promise represents a value which may be available now, or in the future, or never.
  • A Promise is in one of these states:
  • pending: initial state, not fulfilled or rejected.
  • fulfilled: meaning that the operation completed successfully.
  • rejected: meaning that the operation failed.

  • As the Promise.prototype.then() and Promise.prototype.catch() methods return promises, they can be chained.

  • Definition
    Syntax
    new Promise( /* executor */ function(resolve, reject) { ... });

    Parameters
  • executor
  • A function normally initiates some asynchronous work, and then, once that completes, either calls the resolve function to resolve the promise or else reject it if an error occurred.
  • If an error is thrown in the executor function, the promise is rejected. The return value of the executor is ignored.
  • Because the work is an asynchronous work, you may use XHR or Fetch in it.


  • Methods
  • reject(reason) - return a promise with the given reason.
  • resolve(value) - return a promise that is resolved with the given value. The value maybe a promise too, if it is, chain the result with then method again.

  • Prototype Methods
  • prototype.catch(onRejected) - onRejected is a callback function to handle the situation that is on rejected.
  • prototype.then(onFulfilled, onRejected) - OnRejected is as the below catch method. OnFulfilled is a callback function to handle the situation that is on fulfilled.

  • FormData
    Overview
  • The FormData interface provides a way to easily construct a set of key/value pairs representing from fields and their values, which can then be easily sent using asynchronous way(XHR or Fetch).
  • It uses the same format a form would use if the encoding type were set to "multipart/form-data".

  • Definition
    Constructor
  • FormData() Create a new FormData object.

  • Methods
  • append()
  • delete()
  • entries()
  • get()
  • getAll()
  • has()
  • keys()
  • set()
  • values()

  • Fetch API
    Overview
  • The Fetch API provides an interface for fetching resources(including across the network).
  • It will seem familiar to anyone who has used XHR, but the new API provides a more powerful and flexible feature set.

  • Definition
    Interfaces
  • GlobalFetch
  • fetch()

  • Headers
  • Request
  • implement Body

  • Response
  • implement Body


  • Mixin
  • Body
  • json() Takes a Response stream and reads it to completion.It returns a promise that resolves with a JSON object.(fetchが返すResponseを読み取り処理し、json Object化されたresponseを得る.この処理は非同期処理であるため、戻りはPromiseである.またfetch自体は非同期操作であり、得られるResponseも当然Promiseである.)


  • Restful API Design
  • POSTを使用してリソースを作成するには、認証が必要になることが多い.認証tokenをrequestのheaderに入れ、作成データをrequestのbodyに入れ、送信する必要がある.tokenはheaderの「Authorization」fieldに入れ、前に「Bearer」タイプの表示を付けます.作成データはFormDataに入れ、formDataをbodyに戻すことが多い.
  • 返された結果がjson形式のデータである場合、headerの「Accept」fieldの値を「アプリケーション/json」と書く必要がある.

  • WorkFlow
  • Get token from localStorage to post a image by fetch API.(assume the token is there.)
  • Get the remote url of the image in response.
  • Show image.

  • Demo
    https://jsfiddle.net/clemTheD...
    Reference
    PromiseFetchFormData