1 //function function: Create a random integer within 10 after 1 seconds, and determine if the number is even, and if it is even, do one thing, and if it is odd, do another thing .2 functiondosomthing () {3 varPromise =NewPromise (function(Resolve, reject) {4SetTimeout (function () {5Const num = Math.Round (math.random () * 10);6 if(num% 2 = = = 0) {7 resolve (num);8}Else {9 reject (num);Ten } One}, 1000); A }); - returnpromise; -}
1 //call the method, get the Promise object, and pre-specify the successful and failed callback function before the thing in promise is done2 //successful and failed callback functions, which correspond to the resolve and reject in the anonymous function passed by the new Promise object, respectively ,3Dosomthing (). Then (function(val) {4Console.log (' First even number: ' +val);5 returnDosomthing ();//when things are done, you can return a new promise object and continue to use. Then specify the next callback function6},function(val) {7Console.log (' first odd: ' +val);8 returndosomthing ();9}). Then (function(val) {TenConsole.log (' Second even: ' +val); One returndosomthing (); A},function(val) { -Console.log (' second odd: ' +val); - returndosomthing (); the}). Then (function(val) { -Console.log (' Third even: ' +val); -},function(val) { -Console.log (' third odd: ' +val); +});
Promise Summary:
- Promise means to do one thing, to do something that needs to be specified at the time of the new Promise object
- Once the Promise object is new, it will immediately do what is specified in the Promise object (so if you do not want to do this immediately, you can put the new Promise object's procedure in one method)
- There is a process of doing everything, so before we do anything in this promise, we don't know whether the result of the final execution is success or failure.
- But we can be sure that after this thing is done, there must be a result of the execution, either it succeeds, or it fails, and the result of the execution is related to the operation;
- Therefore, we can advance for this promise object, through the Resolve method to specify the processing function after success, through the Reject method to specify the processing function after the failure
- So, how do you specify the resolve and reject functions in advance? You can invoke the. Then (Success callback function, failed callback function) method in the Promise object to pre-specify the success and failure handler!
- This way, when things in the Promise object are done, a predefined success or failure handler is invoked
- Inside a successful and failed handler, you can create a new promise object to perform the next thing and specify the successful and failed callback function by the next. Then.
Simple use of promise in JavaScript