javaScript basics summary (xiv)

1, the callback

  What is callback?

  Personal understanding, so that the orderly function of execution.

  Example:

  function loadScript(src,callback){

    let script = document.createElement('script');

    script.src = src;

    script.onload =()=>calllback(script);

    document.head.append(script);

  }

  loadScript('src',script=>{

    alert('ok');

  });

  You can continue to call back in the callback function, but this will lead to the callback pyramid, or hell.

 

2、Promise

  Promise object constructor syntax

  let promise = new Promise(function(resolve,reject){

    //executror

  });

  promise object has an internal property

  State ----- initially pending, then changed to 'fulfilled "or" rejected "

  Result ----- an arbitrary value, initially undefined

  When the executor to complete the task, the application calls one of the following

 

  Consumer: ". Then" and ".catch"

  promise object serves as a connection between the producer and consumer functions.

  .then syntax;

  promise.then(

    function(result){}

    function(error){}

  );

  Example:

  let promise = new Promise(function(resolve,reject){

    setTimeout(()=>resolve("done"),1000);

  });

  promise.then(

    result=>alert(result),

    error=>alert(error)

  );

    In which success and failure can also choose only one, as follows

  Only the success of the operation;

  let promise = new Promise(resolve=>resolve("done!"));

  promise.then(alert);

  There are two operating error

  let promise = new Promise((resolve,reject)=>{

    setTimeout(()=>reject(new Error("cuole!")),1000);

  });

  promise.then(null,alert);

  Shorthand: promise.catch (alert);

  practice

  function loadScript(src){

    return new Promise(function(resolve,reject){

      let script  document.createElement('script');

      script.src = src;

      script.onload=()=>resolve(script);

      script.onerror=()=>reject(new Error("Script load error: " + src));

      document.head.append(script);

    });

  }

  let promise = loadScript('src');

  promise.then(

    script=>alert(`${script.src} is loaded!`),

    error=>alert(`Error:${error.message}`)

  );

  promise.then(script=>alert('one more handler to do something');

 

 3、Promises 链

  Example:

 1 new Promise(function(resolve, reject) {
 2 
 3   setTimeout(() => resolve(1), 1000); // (*)
 4 
 5 }).then(function(result) { // (**)
 6 
 7   alert(result); // 1
 8   return result * 2;
 9 
10 }).then(function(result) { // (***)
11 
12   alert(result); // 2
13   return result * 2;
14 
15 }).then(function(result) {
16 
17   alert(result); // 4
18   return result * 2;
19 
20 });

  .then returns promises

 1 new Promise(function(resolve, reject) {
 2 
 3   setTimeout(() => resolve(1), 1000);
 4 
 5 }).then(function(result) {
 6 
 7   alert(result); // 1
 8 
 9   return new Promise((resolve, reject) => { // (*)
10     setTimeout(() => resolve(result * 2), 1000);
11   });
12 
13 }).then(function(result) { // (**)
14 
15   alert(result); // 2
16 
17   return new Promise((resolve, reject) => {
18     setTimeout(() => resolve(result * 2), 1000);
19   });
20 
21 }).then(function(result) {
22 
23   alert(result); // 4
24 
25 });

Where the first .thendisplay 1and (*)the line return new Promise(…), it will then resolve one second off, then the result ( resolveparameter, here it is result*2) is transmitted to the located (**)row second .then. It will display 2and perform the same action.

The output is 1 → 2 → 4, but now each alerthave a 1 second delay between calls.

  Examples loadScript

. 1 The loadScript ( " /article/promise-chaining/one.js " )
 2    .then (Script => The loadScript ( " /article/promise-chaining/two.js " ))
 . 3    .then (Script => The loadScript ( " / Article This article was / Promise-Chaining / Three.js " ))
 . 4    .then (script => {
 . 5      // script is loaded, we can use the function of the declared 
. 6      One ();
 . 7      TWO ();
 . 8      Three ();
 9    });

  Examples fetch

  The basic syntax: let promise = fetch (url);

  

function loadJson(url) {
  return fetch(url)
    .then(response => response.json());
}

function loadGithubUser(name) {
  return fetch(`https://api.github.com/users/${name}`)
    .then(response => response.json());
}

function showAvatar(githubUser) {
  return new Promise(function(resolve, reject) {
    let img = document.createElement('img');
    img.src = githubUser.avatar_url;
    img.className = "promise-avatar-example";
    document.body.append(img);

    setTimeout(() => {
      img.remove();
      resolve(githubUser);
    }, 3000);
  });
}

// 使用它们
loadJson('/article/promise-chaining/user.json')
  .then(user => loadGithubUser(user.name))
  .then(showAvatar)
  .then(githubUser => alert(`Finished showing ${githubUser.name}`));
  // ...

4、Promise API

  In Promise class, there are five kinds of static method. as follows

  Promise.resolve

  语法:let promise = Promise.resolve(value);

  

 1 function loadCached(url) {
 2   let cache = loadCached.cache || (loadCached.cache = new Map());
 3 
 4   if (cache.has(url)) {
 5     return Promise.resolve(cache.get(url)); // (*)
 6   }
 7 
 8   return fetch(url)
 9     .then(response => response.text())
10     .then(text => {
11       cache.set(url,text);
12       return text;
13     });
14 }

  Promise.reject

  语法: let promise = Promise.reject(error);

  let promise = new Promise((resolve, reject) => reject(error));

  Promise.all

  let promise = Promise.all([...promises...]);

 

. 1  Promise.all ([
 2    new new Promise (Resolve => the setTimeout (() => Resolve ( . 1 ), 3000 )), // . 1 
. 3    new new Promise (Resolve => the setTimeout (() => Resolve ( 2 ), 2000 )), // 2 
. 4    new new Promise (Resolve => the setTimeout (() => Resolve ( . 3 ), 1000 ))   // . 3 
. 5 .]) the then (Alert); // l, 2,3 promise when ready: every promise becomes an array

  Promise.allSettled

  

 1 let urls = [
 2   'https://api.github.com/users/iliakan',
 3   'https://api.github.com/users/remy',
 4   'https://no-such-url'
 5 ];
 6 
 7 Promise.allSettled(urls.map(url => fetch(url)))
 8   .then(results => { // (*)
 9     results.forEach((result, num) => {
10       if (result.status == "fulfilled") {
11         alert(`${urls[num]}: ${result.value.status}`);
12       }
13       if (result.status == "rejected") {
14         alert(`${urls[num]}: ${result.reason}`);
15       }
16     });
17   });

  Promise.race

  语法:let promise = Promise.race(iterable); 

1 Promise.race([
2   new Promise((resolve, reject) => setTimeout(() => resolve(1), 1000)),
3   new Promise((resolve, reject) => setTimeout(() => reject(new Error("Whoops!")), 2000)),
4   new Promise((resolve, reject) => setTimeout(() => resolve(3), 3000))
5 ]).then(alert); // 1

The first result / error will be the entire Promise.raceresult. After the first promise to be resolved ( "win [wins the race]"), the results of all subsequent / errors are ignored.

 

5、Async/await

  Async functions

  async fucntion f(){

    return 1;
  }

  f().then(alert);//1

  async ensure the function return value is a promise.

  Await

  语法:let value = await promise;

  Requirements: await conventional method can not be used, only with another async function.

  

 1 async function showAvatar() {
 2 
 3   // 读取 JSON
 4   let response = await fetch('/article/promise-chaining/user.json');
 5   let user = await response.json();
 6 
 7   // 读取 github 用户信息
 8   let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
 9   let githubUser = await githubResponse.json();
10 
11   // 显示头像
12   let img = document.createElement('img');
13   img.src = githubUser.avatar_url;
14   img.className = "promise-avatar-example";
15   document.body.append(img);
16 
17   // 等待 3 秒
18   await new Promise((resolve, reject) => setTimeout(resolve, 3000));
19 
20   img.remove();
21 
22   return githubUser;
23 }
24 
25 showAvatar();

  In the method using the class

  class Waiter{

    async wait(){

      retrun await Promise.resolve(1);

    }

  }

  new Waiter()

    .wait()

    .then(alert);//1

  

  

Guess you like

Origin www.cnblogs.com/xiaoqiyaozou/p/11505823.html