Promise is a js standard built-in object.javascript
Promise is used for asynchronous computations.java
A Promise represents a value which may be available now, or in the future, or never.json
A Promise is in one of these states:promise
pending: initial state, not fulfilled or rejected.app
fulfilled: meaning that the operation completed successfully.異步
rejected: meaning that the operation failed.async
As the Promise.prototype.then() and Promise.prototype.catch() methods return promises, they can be chained.ide
new Promise( /* executor */ function(resolve, reject) { ... });
executorpost
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.fetch
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.
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.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.
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".
FormData()
Create a new FormData object.
append()
delete()
entries()
get()
getAll()
has()
keys()
set()
values()
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.
GlobalFetch
fetch()
Headers
Request
implement Body
Response
implement Body
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。)
使用POST建立一個資源,每每須要認證,須要把認證token放在request的header裏,把建立數據放到request的body裏,發過去。token要放到header的'Authorization' field裏,而且前面要加'Bearer '類型標示。建立數據每每放到FormData裏,再把formData放倒body裏。
若是返回的結果是json格式的數據,還需把header裏的'Accept' field的值寫成'application/json'.
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.
https://jsfiddle.net/clemTheD...