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
Daily Recommendation