JavaScript asynchronous programming 3 -- chain use of promise

charlee44 2021-05-03 18:26:46
javascript asynchronous programming chain use


summary

In the last article 《JavaScript Asynchronous programming 2—— combination XMLHttpRequest Use Promise》 in , Briefly introduced Ajax And Promise Combined use of . such , We have two examples of asynchronous operations : Read a json file ; Loading images from an address . Think about it , If there are two asynchronous operations , They need to perform one operation before another ( For example, here , We store the image address in json In file , By visiting json To load the image ), How to do it ?

Detailed discussion

1️⃣ Back to hell

In order to realize the functions mentioned above , If we don't use Promise, Of course, it can also be realized by using callback function directly :

$(function () {
var url = "./1.json";
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function () {
if (req.status == 200) {
var imgJson = JSON.parse(req.response);
var img = new Image();
img.onload = function () {
$(img).appendTo($('#container'));
};
img.onerror = function () {
throw new Error("Load Image Error!");
}
img.src = imgJson[0];
} else {
throw new Error(req.statusText);
}
};
req.onerror = function () {
throw new Error("Network Error");
};
req.send();
});

You can see here that we use two layers of nested callbacks , The asynchronous operation of loading images is in XMLHttpRequest Access request response callback , This allows access to json Access the image operation immediately after the request is finished . So let's take it a step further , You need to add a behavior , After loading the image, you can operate it ( For example, image processing )? In this case, we have to add another layer of nested callback functions . such , The program goes from top to bottom , The order from front to back will become from the outside to the inside —— The most intuitive inconvenience is ,"{}" There are more layers , Programs can become hard to read —— And this , It's called “ Back to hell ” 了 .

2️⃣Promise Realization

In order to solve “ Back to hell ” The problem of ,Promise emerge as the times require . As I said in previous articles ,Promise Purpose , I want asynchronous behavior to follow the same order as synchronous operation , To avoid nested callbacks . in other words , As long as the success of each implementation , That is to say then() In the method , Go back to the new Promise object , You can call the Promise Object's then() Method , In this way, asynchronous behavior can be like synchronous operation , Put them together in order . And the combination is chained , From front to back , This avoids multi-layer nesting :

$(function () {
function get(url) {
return new Promise(function (resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function () {
// Even if it's 404 It will also enter the corresponding function , So we need to detect the State
if (req.status == 200) {
// Fulfill the promise , Returns the response text
resolve(req.response);
} else {
// Done not done , Returns an error
reject(Error(req.statusText));
}
};
// The corresponding function in case of an error
req.onerror = function () {
reject(Error("Network Error"));
};
// Send a request
req.send();
});
}
function getImg(uri){
return new Promise(function(resolve, reject){
var img = new Image();
img.onload = function () {
resolve(img);
};
img.onerror = function () {
reject(Error("Load Image Error!"));
}
img.src = uri;
});
}
var addressUri = "./1.json";
get(addressUri).then(function (response) {
var imgJson = JSON.parse(response);
return getImg(imgJson[0]);
}, function (error) {
console.error("Failed!", error);
}).then(function(img){
$(img).appendTo($('#container'));
}, function(error){
console.error("Failed!", error);
});
});

Reference resources

  1. JavaScript Promises: An introduction
版权声明
本文为[charlee44]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210503182421692g.html

  1. CSS layout
  2. Application scenario explanation of Vue dynamic component
  3. Redux learning notes 04 -- using multiple reducers to manage data
  4. After three months of typescript writing, what have I learned?
  5. Node family - what is a callback?
  6. React -- a simple implementation of render & create element
  7. JS learning simple usage of jquery
  8. Seamless love
  9. 小白前端入门笔记(12),设置哑链接
  10. Small white front-end entry notes (12), set dumb links
  11. Vue2. X opens composition API and TSX
  12. Interview record and thinking of social recruitment for one and a half years (Alibaba, Tencent, baidu offer)
  13. Flex learning notes
  14. The most essential closure article in the eastern hemisphere
  15. 2021-05-03 hot news
  16. Sword finger offer -- reverse order pair in array (JS Implementation)
  17. Working process of scaffold
  18. Use decorator mode to strengthen your fetch
  19. [JS] scope (Introduction)
  20. Employment information statistics network (interface document)
  21. Analysis of MVC
  22. [middle stage] please stay and join me in the backstage
  23. Understanding front end garbage collection
  24. [continuous update] front end special style implementation
  25. Flutter product analysis and package reduction scheme
  26. XPath positioning
  27. 前端开发css中的flex布局的使用
  28. The use of flex layout in front end development CSS
  29. JQuery核心函数和静态方法
  30. JQuery core functions and static methods
  31. Node family - understanding of blocking and non blocking
  32. 热点微前端Microfrontend的讨论:谷歌AdWords是真实的微前端
  33. Vue source code analysis (2) initproxy initialization proxy
  34. What's TM called react diff
  35. Summary of common front end data structure
  36. Useeffect in hooks
  37. [encapsulation 02 design pattern] Command pattern, share meta pattern, combination pattern, proxy pattern, strategy pattern
  38. Front end notes: virtual Dom and diff of vue2. X
  39. The best code scanning plug-in of flutter
  40. The simplest plug-in for rights management of flutter
  41. 21. Object oriented foundation "problems and solutions of object traversal"
  42. Discussion on hot micro front end: Google AdWords is a real micro front end
  43. Usecallback and usememo for real performance optimization
  44. 【前端圭臬】十一:从规范看 JavaScript 执行上下文(下)
  45. [front end standard] 11: Javascript execution context from the perspective of specification (2)
  46. Hexagonal六角形架构ReactJS的实现方式 - Janos Pasztor
  47. Transaction of spring's reactive / imperative relational database
  48. The implementation of hexagonal hexagonal reactjs Janos pasztor
  49. HTTP状态码:402 Payment Required需要付款 - mozilla
  50. HTTP status code: 402 payment required - Mozilla
  51. Factory mode, constructor mode and prototype mode
  52. Build the scaffold of react project from scratch (Series 1: encapsulating a request method with cache function based on Axios)
  53. Cocos Quick Start Guide
  54. Comparison of three default configurations of webpack5 modes
  55. A case study of the combination of flutter WebView and Vue
  56. CSS: BFC and IFC
  57. A common error report and solution in Vue combat
  58. JS: this point
  59. JS: prototype chain
  60. JavaScript series -- promise, generator, async and await