JavaScript Asynchronous Programming Promise pattern 6 features _javascript tips

Source: Internet
Author: User

Before we begin our formal presentation, we'd like to look at the JavaScript promise:

Copy Code code as follows:

var p = new Promise (function (resolve, reject) {
Resolve ("Hello World");
});

P.then (function (str) {
alert (str);
});

1. Then () returns a forked Promise

What is the difference between the following two paragraphs of code?

Copy Code code as follows:

Exhibit A
var p = new Promise (/*...*/);
P.then (FUNC1);
P.then (FUNC2);

Exhibit B
var p = new Promise (/*...*/);
P.then (FUNC1)
. then (FUNC2);

If you're serious about the two pieces of code that are equivalent, then promises is just a one-dimensional array of callback functions. However, this is not the case. Each then () call returns a forked promise. Therefore, in Exhibita, if Func1 () throws an exception, Func2 () is still called normally.

In EXHIBITB, if Func1 () throws an error, fun2 () will not be invoked because the first call returns a new promise, which is rejected in Func1 (). The result is that Func2 () is skipped.

Summary: Promises can be fork into multiple paths, similar to complex flowcharts.

2. Callback should deliver results

What is the warning when you run the following code?

Copy Code code as follows:

var p = new Promise (function (resolve, reject) {
Resolve ("Hello World");
});

P.then (function (str) {})
. then (function (str) {
alert (str);
});

Alert in the second then () does not display any content. This is because the callback function, in the context of the promise, has no callback function because of the change in the result. Promise expects your callback function to return the same result or return a replacement result, which is then passed to the next callback function.

Similar use of adpater to change results as follows:

Copy Code code as follows:

var feettometres = function (ft) {return ft*12*0.0254};

var p = new Promise (/*...*/);

P.then (Feettometres)
. then (function (metres) {
alert (metres);
});

3. Only exceptions from the previous layer can be caught

What's the difference between these two pieces of code?

Copy Code code as follows:

Exhibit A
New Promise (function (resolve, reject) {
Resolve ("Hello World");
})
. Then (
function (str) {
throw new Error ("Uh oh");
},
Undefined
)
. Then (
Undefined
Function (Error) {
alert (error);
}
);

Exhibit B
New Promise (function (resolve, reject) {
Resolve ("Hello World");
})
. Then (
function (str) {
throw new Error ("Uh oh");
},
Function (Error) {
alert (error);
}
);


In the first code, the exception in the first then () is thrown and will be caught by the second then (), and then the "Uh Oh" warning will be triggered. This follow only the previous level of the exception will be captured.

In the second code, the callback function and the error callback function are at the same level, meaning that when the exception is thrown in the callback, it will not be caught. In fact, the error callback for the second piece of code will only be thrown if the promise is rejected or the promise itself fails

4. Errors can be restored

In an error callback function, if you do not throw the error back, promise assumes that you have recovered from the error and that the reversal has been resolved. In the next example, "I ' M saved" will be displayed because the error callback in the first then () does not throw the exception back.

Copy Code code as follows:

var p = new Promise (function (resolve, reject) {
Reject (New Error ("Pebkac"));
});

P.then (
Undefined
Function (Error) {}
)
. Then (
function (str) {
Alert ("I am saved!");
},
Function (Error) {
Alert ("Bad computer!");
}
);

Promise can be seen as layers on onions. Each then () adds another layer to the onion. Each level represents an activity that is handled. When the hierarchy is over, the result is thought to have been repaired and ready for the next level.

5. Promises can be suspended

Because you're ready. Executing in a then () method does not mean that you are not able to pause and run the other in advance. In order to suspend the current promise, or let it wait for another promise to complete, simply return another promise in then ().

Copy Code code as follows:

var p = new Promise (/*...*/);

P.then (function (str) {
if (!loggedin) {
return new Promise (/*...*/);
}
})
. then (function (str) {
Alert ("Done.");
})

In the preceding code, the prompts do not appear until the new promise resolves. This is a convenient way to introduce more dependencies in an existing asynchronous code path. For example, you may find that the user session has been timeout, and you may want to initialize the second login before continuing the previous code path.

6. Resolved promises will not be implemented immediately

Do you get a cue box to run the following code?

Copy Code code as follows:

function Runme () {
var i = 0;

New Promise (function (resolve) {
Resolve ();
})
. then (function () {
i + 2;
});
alert (i);
}

Because promise is parsed immediately, then the then () method is executed immediately, so you may think that Tip 2 will be detected. However, the promise definition requires that all calls be coerced asynchronously. Therefore, the prompts are generated before being modified.

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.