Asynchronous and promise

Zhiyou 2021-09-15 09:08:39
asynchronous promise

What is asynchronous ? What is synchronization


If you can get the results directly , It's synchronization ;

give an example : Register at the hospital site , Get the number before you leave the window .

If you can't get the results directly , It's asynchronous .

give an example : Wait at the restaurant door , After you get the number, you can go shopping

When can we really eat ?

You can every 10 Go to the restaurant and ask in minutes ( polling )

You can also scan the code and use wechat to receive notifications ( Callback )

Callback callback

Write but don't call , Functions called to others , It's a callback .

give an example :

Put function 1 Give another function 2

function f1(){}
function f2(fn){
 Copy code 

analysis :

  • I called f1 No, ? answer : There is no call
  • I put f1 Pass to f2( others ) Have you ? answer : Yes
  • f2 Called f1 No, ? answer :f2 Called f1
  • that ,f1 I wrote it to f2 Called function , therefore ,f1 It's a callback .

The relationship between asynchrony and callback


  • Asynchronous tasks need to be notified when they get results JS Here's the result
  • How to inform ?
  • It can make JS Leave a function address for the browser
  • When the asynchronous task is completed, the browser can call the function address
  • At the same time, the result is passed to the function as a parameter
  • This function I wrote to the browser to call , So it's a callback function


  • Asynchronous tasks need to use callback functions to notify results , You can also use polling
  • But callback functions don't have to be used only in asynchronous tasks
  • Callbacks can be used in synchronization tasks
  • arry.forEach(n => console.log(n)) It's synchronous callbacks

Judge synchronous and asynchronous

If the return value of a function is in

  • setTimeout
  • AJAX( namely XMLHttpRequest)
  • AddEventListener
  • If the return value is inside these three things , So this function is asynchronous

AJAX Can be set to synchronous , But doing so will cause the page to get stuck during the request , Do not use .

give an example 1

function Dice (){
return parseInt(Math.random() * 6)+1},1000)
// return undefined
 Copy code 


  • Dice () Didn't write return, That's it return undefined
  • The arrow function has return, Return to the real result
  • So this is an asynchronous function / Asynchronous task

give an example 1 To continue

const n = Dice ()
console.log(n) //undefined
 Copy code 

How to get asynchronous results

  • answer : You can use callback . Write a function , Then give it the function address
function f1(x){console.log(x)}
Dice (f1)
 Copy code 
  • Then I asked the roll dice function to get the result and pass the result as a parameter to f1
function Dice (fn){
fn(parseInt(Math.random() * 6)+1)},1000)
 Copy code 

Simplified arrow function

because f1 Only once after the declaration , So you can delete f1

function f1(x){console.log(x)}
Dice (f1)
 Copy code 

Change to

 Dice (x => {
 Copy code 

Simplify it to

 Dice (console.log)
// If the number of parameters is inconsistent, it cannot be simplified like this 
 Copy code 


  • Asynchronous tasks don't get results
  • So we send a callback to the asynchronous task
  • Call the callback when the asynchronous task is completed
  • When called, take the result as a parameter

If an asynchronous task has two results , Success or failure , What do I do

Two results

  • Method 1 : The callback takes two parameters
fs.readFile('./1.txt',(error, data)=>{
if(error){console.log(' Failure '); return}
console.log(data.toString()) // success 
 Copy code 
  • Method 2 : Pass two callbacks
ajax('get', '/1.json', data()=>{}, error()=>{})
// The previous function is a successful callback , The following function is the failure callback 
Another form :
ajax('get', '/1.json', {
success: ()=>{}, fail: ()=>{}
// Accept an object , There are two objects key Indicates success and failure 
Callbacks don't have to be in the form of functions , You can also use the form of objects
 Copy code 
  • The shortcomings of these methods

Whether method one or method two , All have problems

  1. No specification , There are many different names , Someone uses it success+error, Someone uses it success+fail, Someone uses it done+fail
  2. Prone to callback hell , The code becomes unintelligible
  3. It's hard to do error handling


promise It is a unified solution for the front-end to solve asynchronous problems

With AJAX For example , explain Promise Usage of

ajax = (method, url, options)=>{
const {success, fail} = options // An analytic assignment 
const request = new XMLHttpRequest(), url)
request.onreadystatechange = ()=>{
if(request.readyState === 4){
// If successful, call success, Fail to call fail
if(request.status < 400){, request.response)
}else if(request.status >= 400){, request, request.status)
 Copy code 
ajax('get', '/xxx', {
success(response){}, fail: (request, status)=>{}
}) // On the left is function abbreviation , On the right is the arrow function 
 Copy code 

Change to Promise How to write it

ajax('get', '/xxx', {
success(response){}, fail: (request, status)=>{}
// Two callbacks are used above , Also used. success and fail
// Change to promise How to write it 
ajax('get', '/xxx')
.then((response)=>{}, (request)=>{}) //promise Specifies that both successful callback and failed callback can only accept one parameter 
 Copy code 

Although it is also a callback , But you don't need to remember success and fail 了 ;

then The first parameter of is success,then The second parameter of is fail;

ajax() Returns a message containing .then() Object of method ,

So how do you get this containing .then The object of ?

Then we need to transform ajax Source code

ajax = (method, url, options)=>{
return new Promise((resolve, reject)=>{
const {success, fail} = options
const request = new XMLHttpRequest(), url)
request.onreadystatechange = ()=>{
if(request.readyState === 4){
// If successful, call resolve, Fail to call reject
if(request.status < 400){, request.response)
}else if(request.status >= 400){, request)
 Copy code 


How to turn the asynchronous function of a callback into promise The asynchronous function of ?

  1. First step
  • return new promise ((resolve, reject)=>{...})
  • If the task succeeds, call resolve(result)
  • If the task fails, call reject(error)
  • resolve and reject The success and failure functions are called again

resolve and reject Not at all .then(success, fail) Inside success and fail,resolve call success,reject call fail.

  1. The second step
  • Use .then(success, fail) Pass in success and failure functions

promise More advanced usage , And then more

The above encapsulated AJAX The shortcomings of

  • post Unable to upload data

request.send( Here you can upload data )

  • Cannot set request header

request.setRequestHeader(key, value)

  • How to solve

Use jQuery.ajax ( although jQuery.ajax Very perfect and powerful , But it's out of date , More in use axios)

Use axios( For reference, Fang Yinghang blog

Expand your knowledge :

promise It can't be cancelled , however axios May cancel , because axios Invented cancelToken.


  1. Contrôle de l'arbre en vue converti en style de table
  2. CSS3 animation flash Effect
  3. Discuter des propriétés de la file d'attente pour l'événement bloc
  4. Node around USModules
  5. Webpack - - Premier aperçu (concept de base)
  6. Mise en œuvre du cadre de base mvvm par JS natif
  7. Calculer les propriétés par rapport aux auditeurs, etc.
  8. Configuration standard dockerfile et docker-composer.yml
  9. Collection de questions d'entrevue HTML
  10. Conteneur, définir la largeur et la hauteur ne répond pas?
  11. Introduction et syntaxe des objets (mise à jour à long terme)
  12. Bubble Mart invests in cat galaxy, which is a vertical e-commerce platform around the quadratic element
  13. Exigences et dépendances dans package-lock.json
  14. Mouvement tridimensionnel de la terre, du ciel et de la lune basé sur three.js
  15. Compréhension et analyse de l'objet de base JS
  16. Simple use of status data management (context, mobx, Redux)
  17. Simulated drumming
  18. Array method
  19. Performance optimization issue 03 - HTTP request optimization
  20. Vue learning -- watch listener
  21. Learn more about nexttick in Vue
  22. Talk about some moves used by vue3.0 in the project - External skill chapter (I)
  23. JavaScript genrator generator
  24. La dernière réponse à l'entrevue de développement Android, l'hiver froid de l'industrie
  25. Maserati's motorcycle has less than 10 in the world. It is definitely a work of art
  26. 2021 partage des questions du dernier examen écrit d'entrevue Android, pas d'accord
  27. Programmation asynchrone Java scirp, développement frontal de base
  28. 2021 dernier examen écrit d'entrevue Android, écrit trop bien
  29. Quels aspects doivent être pris en considération dans le tableau principal du distributeur libre - service?
  30. He inherited his mother's hundreds of millions of property for his boyfriend to squander. Unexpectedly, he was ruthlessly abandoned when he had 100 yuan left
  31. The fuel cost is half less than that of fuel vehicles at the same level. Is it really cheap to use song Pro DM?
  32. Le dernier résumé de l'expérience d'entrevue d'embauche de l'école Android de l'usine est nécessaire pour l'usine
  33. Le dernier dictionnaire avancé de programmeurs d'usine, l'expérience d'entrevue d'embauche de l'Agence de développement Android
  34. La dernière collection d'entrevues Android Golden nine Silver ten
  35. L'expérience d'entrevue de l'Ingénieur d'algorithme de saut d'octets, 2 mois d'entrevue Tencent, station B, Netease et ainsi de suite sur 11 entreprises résumé!
  36. La dernière collection d'entrevues d'Android Golden nine Silver ten recommande un projet github
  37. Yuan Li's recent situation revealed that he was obsessed with public welfare, dressed simply and fearless, grew fat, and married an 11-year-old husband
  38. Initial experience of template tool plop of [front end Engineering]
  39. Dernière question d'entrevue avancée et réponse d'Alibaba Android, Alibaba P8 vous apprendra en personne
  40. Partage des dernières questions d'entrevue pour Android haute fréquence, Introduction aux compétences d'entrevue pour le développement d'Android
  41. Partager les dernières questions d'entrevue Android haute fréquence avec quelques conseils
  42. About JavaScript modules
  43. Iteratable object and class arrays
  44. Function realization of Vue elementui exporting excel form
  45. Use canvas to realize a small screenshot function
  46. Object oriented programming (2)
  47. Several common value transfer methods between Vue components
  48. Démarrer avec le serveur de base zéro: Hello World
  49. J'a I construit un escalier pour aller sur la lune, combien de façons puis - je poursuivre la sœur Chang'e?
  50. CSS implémente la fonction d'expansion et d'arrimage du Texte multiligne
  51. Varlet CLI | vue3 Component Library Quick Prototyping Tool
  52. Belle vue sur les trois rivières Xiapu
  53. La partie Web qui déploie SharePoint ajoute son propre module de fonctionnalité
  54. React Native (mise à jour à long terme)
  55. La conception et le codage de l'arbre binaire requis pour chaque entrevue d'embauche de la société Java millet;
  56. 10 jours pour obtenir l'offre d'emploi Android d'Alibaba, entrevue Android
  57. A remporté avec succès Byte, Tencent, Pulse offer, 7 ans Java une expérience d'entrevue de baise,
  58. 10大前端常用算法,web应用与开发
  59. Nginx - minimum configuration! You deserve it
  60. Les questions d'entrevue couramment utilisées pour le cadre Java sont - elles prometteuses pour le développement Java?