当前位置:网站首页>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边栏推荐
- 不到一小时,苹果摧毁了15家初创公司
- Bytev builds a dynamic digital twin network security platform -- helping network security development
- 如何获取泛型的类型
- 2022年理财产品的常见模式有哪些?
- ASP.NET CORE Study04
- Sha256 encryption tool class
- Deep learning has a new pit! The University of Sydney proposed a new cross modal task, using text to guide image matting
- cdc同步 如果数据库表的主键发生了变化,会同步成两个数据 还是会同步更新主键呢?
- 攻防世界新手入门hello_pwn
- group_concat学习与配置
猜你喜欢

In less than an hour, apple destroyed 15 startups

Leetcode 705. 设计哈希集合

Remoteviews layout and type restriction source code analysis

Multi dimensional monitoring: the data base of intelligent monitoring

Ugui uses tips (VI) unity to realize vertical line display of string

ASP.NET CORE Study02

pwn入门(1)二进制基础

Source code analysis of ArrayList

EMC RS485 interface EMC circuit design scheme

Given two points and a point with a middle scale, find the coordinates of the point
随机推荐
开源项目维权成功案例: spug 开源运维平台成功维权
UGUI使用小技巧(六)Unity实现字符串竖行显示
Ugui force refresh of layout components
期货开户有门槛吗,如何网上安全的开通期货账户
内部振荡器、无源晶振、有源晶振有什么区别?
MapReduce project case 3 - temperature statistics
最新汇总!30省份公布2022高考分数线
websocket 1 分钟自动断开连接
Unity Editor Extension Foundation, editorguilayout (II)
Mathematical principle derivation of structured light phase shift method + multifrequency heterodyne
ASP.NET CORE Study06
C语言 sprintf函数使用详解
[vi/vim] basic usage and command summary
ASP.NET CORE Study09
Using MySQL database in the express framework of node
【Unity编辑器扩展实践】、查找所有引用该图片的预制体
KDD 2022 | 图“预训练、提示、微调”范式下的图神经网络泛化框架
杰理之wif 干扰蓝牙【篇】
设置Canvas的 overrideSorting不生效
Build your own website (18)