What is? Promise?

* promise Promise
* result :resolve cash reject refuse
* credential then then catch Capture failed
Random output of two sentences
var p = new Promise(function(resolve, reject) { setTimeout(() => { var n = Math
.random(); if (n > 0.5) { resolve(' Buy a villa ') } else { reject(' etc. 40 year ') } }, 3000) }) p
.then(function(res) { console.log(res) // Get cashed in }).catch(err => { console.error(
err) // Refused extension })
promise The role of

* Resolving deferred asynchronous tasks Avoid too deep callback level
Output a sentence every other period of time , It can also be solved with callback function , But the hierarchy is too deep , It's easy to cause hell , But with Promise This problem can be solved

* Using callback function to solve function say(str, time, callback) { setTimeout(() => { console.log(
str); if (callback) { callback(); } }, time) } say(' Hello ', 3000, function() { say(
' Add wechat ', 5000, function() { say(' welcome ', 2000) }) })
You can see the callback function from above , Multiple nesting is required , Too much trouble when there are too many output statements , Too many levels .

* use Promise solve function say(str,time){ return new Promise((resolve,reject)=>{
setTimeout(()=>{ resolve(str); },time) }) } say(' Hello ',3000) .then(res=>{ console.
log(res); return say(' Add wechat ',5000) }) .then(res=>{ console.log(res); return say(
' welcome ',2000) }) .then(res=>{ console.log(res); })
Promise There is no need for multi-layer nesting to solve such problems , Solve the problem of too deep level .

Technology
©2019-2020 Toolsou All rights reserved,
How to prevent Mac put to sleep ? Tell you 4 This is an effective way be based on C# Students' grades / mis solve element-ui The drop-down box of has a value but cannot be selected Student information management system source code -C language VR,AR and MR The difference between these technologies 【 Data structure and algorithm 6】 Stack implementation of comprehensive calculator utilize python Yes monkey Automatic log analysis Laya Wechat games sub package loading Alibaba enterprise email smtp set up ( practice )【Java Details of knowledge points 3】 Serializable and Deserialize