当前位置:网站首页>JS duration and asynchronous function promise
JS duration and asynchronous function promise
2022-06-28 12:27:00 【Flying Behemoth】
《JavaScript Advanced programming 》 Reading notes
time limit
During the creation period, you need to pass in the actuator function as a parameter
let p = new Promise(()=>{})
console.log(p); // Promise {<pending>}1. Contractual status
- undetermined (pending)
- cash (fulfilled, Sometimes called “ solve ”,resolved)
- Refuse (rejected)
2. Control the approximate state by executing the function
Contract status is private , So it can only be operated internally . By calling its two function parameters , Usually named reslove() and reject() . When the status is settled, yes Irreversible Of .
3. Promise.resolve()
You can instantiate a solution period of about . Receive a parameter , You can convert any value into a period , Include error objects . If it is a date , It behaves like an empty package . therefore , It can be said to be an idempotent method .
let p1 = new Promise((resolve, reject) => resolve());
// Equivalent to
let p2 = Promise.resolve(); // Promise {<fulfilled>: undefined}
let p3 = Promise.resolve(3); // Promise {<fulfilled>: 3}
p3 === Promise.resolve(p3); // true
Promise.resolve(new Error('foo')); // Promise {<fulfilled>: Error: foo4. Promise.reject()
If an appointment object is passed in , Then this appointment becomes the reason for it to reject the appointment .
let p1 = new Promise((resolve, reject) => reject());
// Equivalent to
let p2 = Promise.reject(); // Promise {<rejected>: undefined}
Promise.reject(3); // Promise {<rejected>: 3}
Promise.reject(Promise.resolve()); // Promise {<rejected>: Promise}An example method of dating
1. Promise.prototype.then()
Receive two optional parameters :onResolved Handlers and onRejected The handler . Non functional handlers are silently ignored . If there is no return statement displayed , Then pass it back as it is , The default return value undefined. Throwing an exception will return the rejected date .
let p =Promise.resolve('foo');
p.then(() => console.log('res'), () => console.log('rej')); // res
p.then(() => {throw 'bar'}, () => console.log('rej')); // Promise {<rejected>: 'bar'}2. Promise.prototype.catch()
A grammar sugar , Used to add an error handler to an appointment . Only one parameter is received :onRejected The handler . Equivalent to calling Promise.prototype.then(null, onRejected);
3. Promise.prototype.finally()
Used to add to the appointment onFinally The handler , This program will be executed when the period changes to the resolved or rejected state .
4. Non reentrant dating method
When the current period is about to enter the landing state , The handlers associated with this state will only be scheduled , Not immediately . The synchronization code following the program must be executed before the program . Even if the period is about to start with the state associated with the additional handler .
5. Execution order of adjacent handlers
If you add more than one handler to the appointment , When the current state changes , The relevant handlers are executed in the order in which they are added .
let p1 = Promise.resolve();
p1.then(() => setTimeout(console.log, 0, 1));
p1.then(() => setTimeout(console.log, 0, 2));
// 1
// 2Static methods
promise.all()
It will be solved after a group of appointments have been solved . Receive an iteratable object , Return to a new period .
Return value :
- If the parameter passed in is an empty iteratable object , Returns a Completed (already resolved) State of Promise Promise.
- If the parameter passed in does not contain any
promise, Returns a Asynchronous completion (asynchronously resolved) Of Promise. - In other cases, return a In processing (pending) Of Promise. This one returns
promiseThen it will be in allpromiseAll complete or have onepromiseWhen the failure asynchronous To become complete or fail .
promise.race()
Is the mirror image of the first resolved or rejected contract in a set . Receive an iteratable object , Return to a new period . As long as it is the first landing date , It will wrap its resolution value or rejection reason and return a new date .
Serial phase synthesis
Based on the subsequent period, the return value of the previous period is used to concatenate the period .
function compose(...fns) {
return (x) => fns.reduce((promise, fn) => promise.then(fn), Promise.resolve(x));
}The period is about to expand
1. The appointment is cancelled
<body>
<button id="start">Start</button>
<button id="cancel">Cancel</button>
</body>
<script>
class CancelToken {
constructor(cancelFn){
this.promise = new Promise((resolve, reject) => {
cancelFn(() => {
setTimeout(console.log, 0 ,"delayed cancelled");
resolve();
})
})
}
}
const startButton = document.getElementById('start');
const cancelButton = document.getElementById('cancel');
function cancellableDelayedResolve(delay){
setTimeout(console.log, 0, "set delay");
return new Promise((resolve, reject) => {
const id = setTimeout((() => {
setTimeout(console.log, 0, "delayed resolve")
resolve();
}), delay);
const cancelToken = new CancelToken((cancelCallback) =>
cancelButton.addEventListener("click", cancelCallback)
)
cancelToken.promise.then(() => clearTimeout(id));
});
}
startButton.addEventListener("click", () => cancellableDelayedResolve(1000));
</script>2. Schedule notice
class TrackablePromise extends Promise {
constructor(executor) {
const notifyHandlers = [];
super((resolve, reject) => {
return executor(resolve, reject, (status) => {
notifyHandlers.map((handler) => handler(status));
});
});
this.notifyHandlers = notifyHandlers;
}
notify(notifyHandler) {
this.notifyHandlers.push(notifyHandler);
return this;
}
}
let p = new TrackablePromise((resolve, reject, notify) => {
function countdown(x) {
if(x > 0){
notify(`${20 * x }% remaining`);
setTimeout(() => countdown(x -1), 1000);
} else {
resolve();
}
}
countdown(5);
});
p.notify((x) => setTimeout(console.log, 0, 'progress:', x));
p.then(() => setTimeout(console.log, 0, 'completed'));
// ( about 1 Seconds later ) progress: 80% remaining
// ( about 2 Seconds later ) progress: 60% remaining
// ( about 3 Seconds later ) progress: 40% remaining
// ( about 4 Seconds later ) progress: 20% remaining
// ( about 5 Seconds later ) completedAn asynchronous function
1. async
Used to declare asynchronous functions . Can be used in function declarations 、 Function expression 、 Arrow functions and methods . If the asynchronous function uses return Keyword return value ( without return Then return to undefined), The value will be Promise.resolve() Packaged as a contract object .
The return value of an asynchronous function expects an implementation thenable Object of the interface , Regular values can also . If the return is an implementation thenable Object of the interface , It can be done by then() “ Unpack ”. If not , Then the return value is regarded as the settled period .
async function foo() {
return 'foo'
}
foo().then(console.log); // foo
async function bar() {
return ['bar']
}
bar().then(console.log); // ['bar']
async function baz() {
const thenable = {
then(callback) { callback('baz'); }
};
return thenable;
}
baz().then(console.log); // baz
2. await
Pause the execution of asynchronous function code , The waiting period is about to be solved .async/await What really works is await. If the asynchronous function does not contain await keyword , Its execution is basically the same as that of ordinary functions .
async function foo() {
console.log(await 'foo');
}
foo(); // foo3. await The limitation of
Must be used in asynchronous functions , No more top-level words, such as <script> Used in tags or modules .
Asynchronous function strategy
1. Realization sleep()
async function sleep(delay) {
return new Promise((resolve) => setTimeout(resolve, delay));
}
async function foo() {
const t0 = Date.now();
await sleep(1500);
console.log(Date.now() - t0);
}
foo(); // 15142. Use parallel execution
async function randomDelay(id) {
const delay = Math.random() * 1000;
return new Promise((resolve) => setTimeout(() => {
console.log(`${id} finished`);
resolve(id);
}, delay));
}
async function foo() {
const t0 = Date.now();
const promises = Array(5).fill(null).map((_, i) => randomDelay(i));
for(const p of promises) {
console.log(`awaited ${await p}`);
}
console.log(`${Date.now() - t0} ms elapsed`);
}
foo();
// 2 finished
// 1 finished
// 4 finished
// 3 finished
// 0 finished
// awaited 0
// awaited 1
// awaited 2
// awaited 3
// awaited 4
// 945 ms elapsed3. The serial execution period is about
async function addTwo(x) {
return x + 2;
}
async function addThree(x) {
return x + 3;
}
async function addFive(x) {
return x + 5;
}
async function addTen(x) {
for( const fn of [addTwo, addThree, addFive]) {
x = await fn(x);
}
return x;
}
addTen(9).then(console.log); // 19边栏推荐
猜你喜欢

Login interface accesses and clears the token

JNI confusion of Android Application Security

ASP.NET CORE Study08

最新汇总!30省份公布2022高考分数线

【C语言】关于scanf()与scanf_s()的一些问题

Leetcode 705. 设计哈希集合

KDD 2022 | graph neural network generalization framework under the paradigm of "pre training, prompting and fine tuning"

pwn入门(1)二进制基础

UGUI使用小技巧(六)Unity实现字符串竖行显示

RemoteViews布局和类型限制源码分析
随机推荐
After importing resources, unity also manually modifies the properties of resources? This code can save you a lot of time: assetpostprocessor
Unity导入资源后还手动修改资源的属性?这段代码可以给你节约很多时间:AssetPostprocessor
【Unity编辑器扩展基础】、EditorGUILayout (一)
Levels – virtual engine scene production "suggestions collection"
攻防世界新手入门hello_pwn
Pyqt5 visual development
In less than an hour, apple destroyed 15 startups
What are the common modes of financial products in 2022?
PyQt5可视化开发
SHA256加密工具类
微信授权登陆
自定义标题栏View
It really doesn't matter if a woman fails to pass the college entrance examination and buys thousands of villas in a counter attack
Many benefits of SEO optimization are directly related to traffic
杰理之wif 干扰蓝牙【篇】
Ugui force refresh of layout components
搭建学习环境
【Unity编辑器扩展基础】、GUI
【Unity编辑器扩展基础】、GUILayout
C语言 sprintf函数使用详解