Promise,ajax,fetch

Source: Internet
Author: User
Tags iterable send cookies

First, promise related

Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise

http://liubin.org/promises-book/#chapter1-what-is-promise

The new Promise (/
    * Executor:executor is a function with resolve and reject two parameters. *
    /function (resolve, reject) {...}
);
Change the state of promise to fulfilled (complete) when the Resolve function is invoked
Change the state of the promise to rejected (failed) when the Reject function is invoked.

A promise has the following three states:
Pending: Initial state, not a success or failure state.
Fulfilled: means the operation completed successfully.
Rejected: means the operation failed.


When the state of a Promise object pending a state and passes a value to the corresponding state-handling method, the processing method (handlers) of the then method binding of the Promise object is invoked (the then method contains two parameters: Onfulfilled and Onrejected, they are all Function types. When the promise State is fulfilled, the then onfulfilled method is invoked, and the Promise method is invoked when the rejected status is then, so there is no competition between the completion of the asynchronous operation and the binding processing method.


Promise.all (iterable)
The success is triggered when all promise objects in the Iterable parameter object are successful, and a failure triggers the failure of the promise object immediately. After the successful state is triggered, the new Promise object takes an array containing all the promise return values in the iterable as the return value of the successful callback, in the order consistent with the iterable order, and if the new Promise object triggers a failed state, It will take the error message of the first promise object that triggers a failure in iterable as its failure error message. The Promise.all method is often used to handle the state collection of multiple Promise objects.
Promise.race (iterable)
When either of the promise in the iterable argument succeeds or fails, the parent promise immediately invokes the corresponding handle to the parent promise binding as a parameter and returns the Promise object with the promise's successful return value or failure details.
Promise.reject (reason)
Returns a Promise object with a state of failure and passes the given failure information to the corresponding processing method
Promise.resolve (value)
Returns a Promise object in which the state is determined by the given value. If the value is a Promise object, the object is returned directly, or if the value is thenable (that is, an object with a then method), the final state of the returned promise object is determined by the then method, otherwise (the value is empty, Base type or an object without the then method, the returned Promise object state is fulfilled and the value is passed to the corresponding then method. In general, if you do not know whether a value is a Promise object, use Promise.resolve (value) to return a Promise object, so that the value can be used as a promise object.

Chestnuts:

var myfirstpromise = new Promise (function (resolve, reject) {
    //when the execution of the asynchronous code succeeds, we invoke resolve (...) and call reject when the asynchronous code fails ( ...)
    In this case, we use the settimeout (...) To simulate asynchronous code, the actual encoding may be the XHR request or some HTML5 API methods.
    settimeout (function () {
        resolve ("Success!");//code executes normally. }
)

; The value of the Myfirstpromise.then (function (successmessage) {
    //successmessage is the above call Resolve (...) The value that the method passes in.
    The successmessage parameter is not necessarily a string type, here is just an example
    console.log ("yay!" + successmessage);
});


Second, Fetch

The

Https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalFetch/fetch
Fetch () method is used to initiate a request to obtain a resource. It returns a promise, which is resolve when the response is requested and returned to the Response object.
When a network error is encountered, the promise returned by the fetch () is reject and returned to TypeError, although this may also be caused by permissions or other issues. A successful fetch () Check should include not only promise being resolve, but also the Response.ok property being true. The HTTP 404 status is not considered a network error.


promise<response> Fetch (input[, Init]);
input may be a usvstring string containing the URL of the resource to be fetched; it may also be a request object. The request interface for the
Fetchapi is used to represent resource requests.
Properties:
Request.method: The method that is requested (get, POST, etc.)
Request.url: The URL that the request uses.
Request.headers: The Headers object that the request is associated with.
, and so
methods:
Request.clone (): Creates a copy of the current Request.
, and so
returns the Response object when the value
is promise,resolve.

var myimage = document.queryselector (' img ');//html5 new Method
var myrequest = new Request (' flowers.jpg ');//var myrequest = new Request (' flowers.jpg ', myinit);
Fetch (Myrequest). Then (function (response) {return
  response.blob ();
}). Then (function (response) {
  var objecturl = url.createobjecturl (response);
  MYIMAGE.SRC = Objecturl;
});

var myimage = document.queryselector (' img ');
var myheaders = new Headers ();
Myheaders.append (' Content-type ', ' image/jpeg ');
var Myinit = {method: ' Get ',
               headers:myheaders,
               mode: ' Cors ',
               cache: ' Default '};
var myrequest = new Request (' flowers.jpg ');
Fetch (Myrequest,myinit). Then (function (response) {
  ... 
});

The main advantages of the Fetch are:
Concise syntax, more semantic
Based on standard Promise implementation, support async/await
Isomorphism convenient, use Isomorphic-fetch
Fetch Common Pits
The fetch request is by default without a cookie, and you need to set fetch (URL, {credentials: ' include '})
When the server returns a 400,500 error code, it does not reject, and the fetch is reject only if the network error causes the request to not complete.
IE usage Strategy
All versions of IE do not support native FETCH,FETCH-IE8 will automatically use XHR to do polyfill. However, there is a problem that needs to be addressed when crossing the domain.
IE8, 9 XHR does not support CORS Cross-domain, although providing xdomainrequest, but this thing is a toy, does not support the passing of cookies. If the interface requires permission validation, use the Jsonp bar quietly.

Three, Ajax and fetch comparison

The fetch is called the next generation Ajax technology, unlike Ajax, its API is not an event mechanism, but it is handled in a Promise manner, and is not currently a standard for the consortium

The essence of Ajax is to use the XMLHttpRequest object to request data
A fetch is a method of the global volume window, and its main features are:
1, the first parameter is the URL:
2, the second is an optional parameter, you can control the different configuration of the Init object
3. Use JavaScript promises to process results/callbacks:

Difference:
1. The Promise returned from fetch () will not reject the HTTP error status, even if the response is an HTTP 404 or 500. Instead, it is resolved normally (where the OK state is set to false) and it is rejected only if a network failure or any blocking request completes.
2. By default, the fetch does not send or receive any cookies on the server, and if the site relies on maintaining a user session, it causes an unauthenticated request (to send cookies, the credential headers must be sent).
If you want to automatically send cookies in the same domain, plus the credentials same-origin option

Fetch (URL, {
  credentials: ' Same-origin '
})
The Same-origin value makes the fetch processing cookie similar to the XMLHttpRequest. Otherwise, cookies will not be sent, causing these requests not to retain the authentication session.
For cors requests, use the include value to allow credentials to be sent to another domain:
Fetch (URL, {
  credentials: ' Include '
})

Four, async/await

ES7 's async/await.

Turn from: http://cnodejs.org/topic/5640b80d3a6aa72c5e0030b6

Chestnuts:

Here we want to implement a pause function, enter n milliseconds, then pause n milliseconds before proceeding down.

var sleep = function (time) {return
    new Promise (function (resolve, reject) {
        settimeout (function () {
            Resolve ();
        }, time);
    })
};

The var start = Async function () {
    try {
	//is used here as intuitive as the sync code
        console.log (' start ');
        Await sleep (3000); Here's a return error
        
        //So the following code will not be executed
        console.log (' End ');
    } catch (Err) {
        console.log (err);//Here Catch error ' Error '
    }
};

Start ();

Turn from: https://segmentfault.com/a/1190000007535316
Async says this is a async function that await can only use in this function. Await said to wait for the promise to return the results here, and then continue execution. Await should be followed by a Promise object (of course, other return values do not matter, but will immediately execute, but that would be meaningless ...) )
Async is used to declare that a function is asynchronous, and await is used to wait for an asynchronous method to execute.
Generally, it is assumed that await is waiting for a async function to complete. However, by syntax, await waits for an expression that evaluates to a Promise object or other value (in other words, there is no special qualification). Because the async function returns a Promise object, await can be used to wait for the return value of a async function--which can be said to be await in the same async function, but to be clear, it is actually a return value. Notice that await is not just for the Promise object, it can wait for the result of any expression await wait for something it wants, a Promise object, or other value, and so on.       I have to say first that await is an operator that is used to compose an expression, and the result of an await expression depends on what it waits for.       If it waits for a Promise object, the result of the await expression is what it waits for. If it waits for a Promise object, the await is busy, blocking the following code, waiting for the Promise object resolve, and then getting the resolve value as the result of the await expression's operation. The advantage of async/await is that dealing with a single Promise chain of the then chain does not find the async/await advantage, but if you need to deal with the Promise chain of multiple then, the advantages can be reflected (very interesting, Promise through Then chain to solve the problem of Multi-layer callback, and now use async/await to further optimize it.
Chestnuts:
Suppose a business is completed in multiple steps, each of which is asynchronous and dependent on the results of the previous step. We still use settimeout to simulate asynchronous operations:

function DoIt () {
    console.time ("doIt");
    Const TIME1 =;
    Step1 (time1)
        . Then (time2 => Step2 (time2)). Then (Time3 => (step3
        ))
        . Time3 (Result then {
            Console.log (' result is ${result} ');
            Console.timeend ("DoIt");}
        );
DoIt ();
C:\var\test>node--harmony_async_await.
Step1 with +//STEP2 with//STEP3 to//is
900
//doit:1507.251ms

Async function DoIt () {
    console.time ("doIt");
    Const TIME1 =;
    Const TIME2 = await step1 (time1);
    Const TIME3 = await Step2 (time2);
    Const RESULT = await step3 (time3);
    Console.log (' result is ${result} ');
    Console.timeend ("DoIt");
}




DoIt ();


It's amazing.


 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.