Original: Promise imagination to understand

We write a function, simply call this function, passing a string.
It will create and return an instance of a type of Promise.

// 本函数实现的是返回一个promise实例,把传进来的参数字符串作为成功时候的捕获值
function doapi(string){
    let p = new Promise(
        (resolve,reject)=>{
            setTimeout(()=>{
                typeof string == 'string' && resolve(string);
            },10000)
        }
    )
    return p;
}

promise instance can be said to be an object, think of it as a person, you let him inside to do things, to grow, he might grow up to 10 seconds to complete, may also be 2 seconds to 10 seconds is possible.
And specify a callback function after the completion of his growth. He is designated after completion of growth will immediately do something.
That is promise.then (() => {//} function body);

E.g

doapi('一斤龙虾')//调用函数,返回一个promise实例,这里称为第1个promise实例
 //给promise实例设置回调函数
.then(
  (a) => {
      //拿到a
      console.log( a )
  }
 )
 //以上第1个promise实例的then方法返回的是一个不用做什么异步操作的promise实例,这里称为第2个promise实例,
 //因为“不用做什么异步操作”所以第2个promise实例已经是完成状态,
 //给以上返回的这第2个promise实例指定回调函数,它不会往回调里传递参数,因为“不用做什么异步操作”
 .then(
   (a) => {
         console.log(a);//undifend
     }
 )

In the browser console where you can see the return value

1. When we call the function when doapi
return an instance of promise


7236116-6052e44057f5c86e.png
image.png
7236116-33e6475f6a3fff3e.png
image.png

In order to facilitate this promise view the status change object instance, I use a variable to store his address

7236116-e4793c872a1c9ded.png
image.png

promise instance method invocation then specify a callback function, then the function's return value is the promise of a new instance created. Referred to here as the second instance of promise, promise that the second instance of the default state is completed, the value is not captured, that you can specify a callback function to it then in

7236116-684ef39c9b8b05c4.png
image.png
7236116-8cc6be937365d0e2.png
image.png
7236116-2ea9ecec12155321.png
image.png

let doapi03 = doapi('一斤龙虾')//调用函数,返回一个promise实例,这里称为第1个promise实例
 //给promise实例设置回调函数
.then(
  (a) => {
      //拿到a
      console.log( a )
      return '2斤肥牛'
  }
 )
 //返回新建立的第2个promise实例,这个promise的成功时的值为上一个then里return的值,默认是undefined,这里return的是'2斤肥牛'
 //以下给这第2个promise实例指定回调函数,这个promise实例的“成功值”会传进去回调函数里
 .then(
   (a) => {
         console.log(a);//'2斤肥牛'
     }
 )
 //返回一个第3个promise实例,其成功值是默认值undefind
 //then方法的返回值默认是一个promise对象,不过没有传出的值,就是没有捕获值,如需捕获值要手动return返回

Reproduced in: https: //www.jianshu.com/p/1b263edc9768

Guess you like

Origin blog.csdn.net/weixin_33912638/article/details/91204850