当前位置:网站首页>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边栏推荐
猜你喜欢

. Net hybrid development solution 24 webview2's superior advantages over cefsharp

为什么CAD导出PDF没有颜色

UGUI使用小技巧(六)Unity实现字符串竖行显示
Three ways to implement LRU cache (recommended Collection)

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

已知两个点和中间一个比例的点,求该点坐标
![[unity Editor Extension practice] dynamically generate UI code using TXT template](/img/20/1042829c3880039c528c63d0aa472d.png)
[unity Editor Extension practice] dynamically generate UI code using TXT template

RemoteViews布局和类型限制源码分析

几百行代码实现一个 JSON 解析器

Ugui uses tips (VI) unity to realize vertical line display of string
随机推荐
【Unity编辑器扩展实践】、查找所有引用该图片的预制体
【Unity编辑器扩展实践】、通过代码查找所有预制
MapReduce project case 3 - temperature statistics
[unity Editor Extension practice] find all prefabs referencing this picture
PrecomputedTextCompat用法及原理
CDC synchronization if the primary key of a database table changes, will it be synchronized into two data or will it be synchronized to update the primary key?
ByteV搭建动态数字孪生网络安全平台----助力网络安全发展
group_concat学习与配置
Unity导入资源后还手动修改资源的属性?这段代码可以给你节约很多时间:AssetPostprocessor
Asynctask experience summary
双缓冲绘图
KDD 2022 | graph neural network generalization framework under the paradigm of "pre training, prompting and fine tuning"
Custom title bar view
Given two points and a point with a middle scale, find the coordinates of the point
杰理之wif 干扰蓝牙【篇】
Leetcode 705. 设计哈希集合
Wechat authorized login
女子高考落榜读专科逆袭买千万别墅,考得不好真的没关系
如何获取泛型的类型
js 期约与异步函数 Promise