当前位置:网站首页>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边栏推荐
- 微信授权登陆
- [C language] use of nested secondary pointer of structure
- Three ways to implement LRU cache (recommended Collection)
- 杰理之wif 干扰蓝牙【篇】
- 【Unity编辑器扩展实践】、通过代码查找所有预制
- group_concat学习与配置
- 分页样式 flex设置成在尾部显示(即使页数加长 也不会因为在末尾而换行)
- 开源项目维权成功案例: spug 开源运维平台成功维权
- ASP.NET CORE Study07
- Levels – virtual engine scene production "suggestions collection"
猜你喜欢

攻防世界新手入门hello_pwn

UGUI强制刷新Layout(布局)组件

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

登录接口存取token,清除token

ASP.NET CORE Study09

Redis principle - List

From simplekv to redis
![[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

MATLAB的官方网站上其实有很多MATLAB的学习和使用资料(文档、视频都有不少)

几百行代码实现一个 JSON 解析器
随机推荐
吐血推荐17个提升开发效率的“轮子”
洛谷_P1303 A*B Problem_高精度计算
[vi/vim] basic usage and command summary
杰理之wif 干扰蓝牙【篇】
【C语言】NextDay问题
Privilege management of vivo mobile phone
搭建学习环境
ASP.NET CORE Study03
2022年理财产品的常见模式有哪些?
从SimpleKV到Redis
ASP.NET CORE Study06
登录接口存取token,清除token
Sha256 encryption tool class
In less than an hour, apple destroyed 15 startups
Levels – 虚幻引擎场景制作「建议收藏」
几百行代码实现一个 JSON 解析器
MATLAB的官方网站上其实有很多MATLAB的学习和使用资料(文档、视频都有不少)
It really doesn't matter if a woman fails to pass the college entrance examination and buys thousands of villas in a counter attack
ASP.NET CORE Study08
多维度监控:智能监控的数据基础