Asynchronous solution (3) Promise

First of all, I suggest that you read this blog post first, which is the clearest and most powerful blog post I have ever seen:

https://www.cnblogs.com/lvdabao/p/es6-promise-1.html

Promises are the most important feature in ES6?

It does. Make callbacks more elegant.

My first company uses jQuery, my second company uses async/await, and my third company uses jQuery and Promises.

In comparison, I still like to use async/await the most, but there were also many UI components written by others that used Promises. Think about it, it came out earlier than ES6, and it was officially certified in ES6, so users should still have the upper hand. .


1. What are the methods of Promise?

Looking at the blog post above, passing consle.dir(Promise)-> Promise is a constructor.

  • own method
    • all (take the longest time)
    • reject
    • resolve
    • race (race, take the shortest time)
  • Methods on the prototype chain
    • In catch -> async/await, try .. catch needs to be used directly, which is a point of ES6 superiority
    • then -> 不用 callback,像 jQuery 的 always/fail/done/then

Since there are methods on the prototype chain, then when new comes out, you can get these methods

let p = new Promise((resolve, reject) => {
  // 一些异步操作
  setTimeout(() => {
    console.log('执行完成');
    resolve('将数据遗留给后人');
  }, 1000);
});

As you can see, the function here is executed directly by itself! ! ! We just define an object and do it ourselves.


2. How to use Promises?

So, we need to wrap a layer of functions around it.
const Invoke = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('执行完成');
      resolve({name: 'Jobs'});
    }, 2000);
  });
};
Invoke();

Through the Invoke function, we realized that it should be shot when it should be shot.

Next, experience passing on fire without callbacks. Infinite callback hell, goodbye.
Invoke().then((data) => {
  console.log(data);
});
Implement it with callback
const fuckPromise = (callback) => {
  setTimeout(() => {
    console.log('先实现一个小目标');
    callback({name: 'Jobs'});
  }, 1000);
};

fuckPromise((data) => {
  console.log(data);
});

For comparison: I divide them into pre-operations and post-operations.

Same point
  • Both subsequent operations are passed as parameters
difference
  • An object is returned in the Promise pre-operation, and there are resolve/reject to control the delivery of data.
  • In the Callback pre-operation, the method parameters are called internally. Leave the data completely to the callback to control.
  • Follow-up operations of Promise, Promise.then()written
  • Subsequent operations to Callback, use外部函数(内部函数)

When there are more levels, the former is a bunch of then, and the latter? ? ? for example! !


3. From callback to Promise.

Callback version 1, when there are more callbacks, we can clearly feel还好我没用4格缩进

let fuckCallback = () => {
  setTimeout(() => {
    console.log('峰哥峰哥,');

    setTimeout(() => {
      console.log('影魔王');
    }, 1000);
  }, 1000);
}

fuckCallback();

Callback version 2: Encapsulate it, the indented code is not so messy, but it is still not intuitive when the amount of data is large.

let callbackOne = (callback) => {
  setTimeout(() => {
    console.log('峰哥峰哥');
    callback();
  }, 1000);
};

let callbackTwo = (callback) => {
  setTimeout(() => {
    console.log('峰哥牛逼');
    callback();
  }, 1000);
};

callbackOne(() => {
  callbackTwo(() => {
    console.log('也许我是下一个操作');
  });
});

Promise version: The code isn't delayed, yes, that's what promises do. It seems useless? It's just not big enough.

const stepOne = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('峰哥峰哥,');
    }, 1000);
  });
};

const stepTwo = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('影魔王!');
    }, 1000);
  });
};

stepOne()
.then((data) => {
  console.log(data);
  return stepTwo();
})
.then((data) => {
  console.log(data);
});

Here, I found a point, in fact, Promises do not matter how you deal with data. At the beginning, you only need to be responsible for implementing the inherited ability of Promises.

Reminds me of the anime "My Hero Academia". The ability of One for All only needs to be inherited. What power to inherit is determined by the contemporary.

4. Other uses of Promise

  • What about returning data directly?
let wrap = () => {
  return new Promise(resolve => {
    resolve({name: 'jobs'});
  });
};

wrap()
.then(data => {
  console.log(data);
  return data;
})
.then(data => {
  console.log('我再传', data);
});
  • Use of reject and catch
let testReject = () => {
  return new Promise((resolve, reject) => {
    const head = Math.random();
    if (head > 0.5) {
      reject('yyf头太大了');
    } else {
      resolve('千军万马避蓝猫');
    }
  });
}

testReject()
.then(data => console.dir(data))
.catch(e => console.error(e));
  • The usage of all (the one with the longest execution time among the two --> execute at the same time, generally used to save the time of the request)
let p1 = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('我会执行两秒钟');
      resolve();
    }, 2000);
  });
};
let p2 = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('我会执行一秒钟');
      resolve();
    }, 1000);
  });
};
Promise
.all([p1(), p2()])
.then(() => console.log('他们都 resolve了,共计时 2s'));

Remember: Promise.all([arg1,arg2,...]) waits for all resolve() to return.

Without the resolve parameter, that doesn't work. You will find that promise.all.then is invalid.

  • race -> race, the first one resolves, then the then operation is performed, and the second one will continue to execute.
Promise
.race([p1(), p2()])
.then(() => console.log('看看过了几秒?'));

Summary: (quote the article at the beginning, copy over there)

Is that all there is to ES6 Promises? Yes, that's basically all you can use.
Why have I seen done, finally, success, fail, etc. What are these? These are not in the Promise standard, but syntactic sugar for our own implementation

Need to continue to follow up on the blog linked at the top.

  • Promise/A+ specification
  • Promises in jquery

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324889007&siteId=291194637