directory
- How to achieve sleep (ES5 or ES6)
- The arrow function this points to the example
- The realization of the Promise. AllSettled
- Event loop Demo – [Resolve or reject in promise]
The constructor
withclass
Within this
The difference between
- Question: what is the reason why the first paragraph of 2) is undefined?
How to achieve the effect of sleep (ES5 or ES6)
(1) While loop
function sleep(ms){
var start=Date.now(),expire=start+ms;
while(Date.now()<expire);
console.log('1111');
return;
}
Copy the code
After executing sleep(1000), 1111 is output after 1000ms sleep. The disadvantages of the above circular way are obvious and easy to cause an endless loop.
(2) Through the promise to achieve
function sleep(ms){
var temple=new Promise(
(resolve) = >{
console.log(111);setTimeout(resolve,ms)
});
return temple
}
sleep(500).then(function(){
//console.log(222)
})
// Output 222 after a delay of 500ms
Copy the code
(3) Encapsulation through async
function sleep(ms){
return new Promise((resolve) = >setTimeout(resolve,ms));
}
async function test(){
var temple=await sleep(1000);
console.log(1111)
return temple
}
test();
// Delay 1000ms output 1111
Copy the code
(4). Generate
function* sleep(ms){
yield new Promise(function(resolve,reject){
console.log(111);
setTimeout(resolve,ms);
})
}
sleep(500).next().value.then(function(){console.log(2222)})
Copy the code
The arrow function “this” points to an example
The arrow function is periodically bound, and the this of the outer function is its own this
1) Ordinary functions
var a=11;
function Test2(){
this.a=22;
console.log('this1:'.this);
let b=function(){
console.log('this2:'.this);
console.log(this.a);
};
setTimeout(function(){
console.log('this3:'.this);
console.log(this.a);
},1000);
b();
}
var t1=new Test2();
Copy the code
You can see that the this inside the constructor all refer to the window
2)In the constructor
thefunction
Instead ofArrow function
var a=11;
function Test2(){
this.a=22;
console.log('this1:'.this);
let b=() = >{
console.log('this2:'.this);
console.log(this.a);
};
setTimeout(() = >{
console.log('this3:'.this);
console.log(this.a);
},1000);
b();
}
var t1=new Test2();
Copy the code
You can see that the arrow inside the constructor all points to its outer constructor Test2.
Three, Promise. AllSettled implementation
1) Review: Promise state
Given an asynchronous operation that returns a Promise, these are the possible states of the Promise:
- Pending: The initial state, which is neither successful nor failed.
- This is a pity: which means that the operation will be completed successfully.
- Rejected: Indicates that the operation fails.
- The hills:
Promise
It’s either done or rejected.Promise
Once achieved, its state does not change.
1.1) What is a combination
Also known as the partial-whole pattern, objects are consolidated into a tree structure to represent a partial-whole hierarchy. The composite pattern makes the use of single objects and composite objects consistent. It is based on two functions:
- Primitive functions (short: primitive) create atomic blocks.
- Combinatorial functions combine atoms and/or composite components to form a composite.
For JS Promises
- Primitive functions include:
Promise.resolve()
,Promise.reject()
- Combinatorial functions:
Promise.all()
.Promise.race()
.Promise.allSettled()
2) Implement allSettled
AllSettled Has a status string for each result object. If its value is fulfilled, there is a value on the result object. If the value is rejected, there is a reason. Value (or Reason) reflects the value of each promise resolution (or rejection).
MyPromise.allSettled = function (promises) {
return new MyPromise((resolve, reject) = > {
promises = Array.isArray(promises) ? promises : []
let len = promises.length
const argslen = len
// If an empty array is passed in, return an empty Resolved array Promise object
if (len === 0) return resolve([])
// Convert the passed argument to an array and assign it to the args variable
let args = Array.prototype.slice.call(promises)
// Calculate whether all promises are currently completed, then resolve
const compute = () = > {
if(--len === 0) {
resolve(args)
}
}
function resolvePromise(index, value) {
// Check whether the incoming type is a promise
if(value instanceof MyPromise) {
const then = value.then
then.call(value, function(val) {
args[index] = { status: 'fulfilled'.value: val}
compute()
}, function(e) {
args[index] = { status: 'rejected'.reason: e }
compute()
})
} else {
args[index] = { status: 'fulfilled'.value: value}
compute()
}
}
for(let i = 0; i < argslen; i++){
resolvePromise(i, args[i])
}
})
}
Copy the code
4. Event loop Demo
1) demo1
Note that the resolve() position in the Promise constructor is executed in the same way as the synchronization task, either before or after resolve in the Promise constructor. Only then is microtask.
console.log('begin')
setTimeout(function () {
console.log('setTimeout 0');
});
new Promise(function (resolve) {
console.log('promise1');
for (let i = 0; i < 1000; i++) {
i === 99 && resolve();
}
console.log('promise2');
}).then(function () {
console.log('then1');
setTimeout(() = > {
console.log('setTimeout2 between promise1&2')
})
}).then(() = > {
console.log('promise 3')});console.log('end')
Copy the code
2) The demo2 Promise state is pending (RESOLVE, reject).
Neither successful nor failed callbacks are executed. Because the only implementation of a Promise that executes resolve or Reject is in the constructor. The state changes. It will be assigned. Note that resolve is commented here. Successful CB after then will not be executed.
console.log('begin')
setTimeout(function () {
console.log('setTimeout 0');
});
new Promise(function (resolve) {
console.log('promise1');
// resolve() Successful CB after then will not be executed.
console.log('promise2');
}).then(function () {
console.log('then1');
setTimeout(() = > {
console.log('setTimeout2 between promise1&2')
})
}).then(() = > {
console.log('promise 3')
}).catch((err) = >{
console.log('reject:', err)
});
console.log('end')
Copy the code
3) demo3 Promise.reject()
The self-executing function executes reject when instantiated, and the failure callback is executed.
Reject A reject callback, which is caught first in then and then in catch. If caught in then, catch will not be caught.
console.log('begin')
setTimeout(function () {
console.log('setTimeout 0');
});
new Promise(function (resolve,reject) {
console.log('promise1');
// resolve() Successful CB after then will not be executed.
reject(0);
console.log('promise2');
}).then(function () {
console.log('then1');
setTimeout(() = > {
console.log('000')
})
}).then(() = > {
console.log('promise 3')},(err) = >{
console.log('Reject :' in the second then, err)
}).catch((err) = >{
console.log('catch reject:, err)
});
console.log('end')
Copy the code
fiveThe constructor
withclass
Within this
The difference between
1) Inside the constructor this
window.name = 'aaa';
function Atest1(){
this.name = 123;
};
Atest1.prototype={
getA() {
console.log(this);
return this.name + 1;
},
getB:() = >{
console.log(this);
return this.name + 1; }}let a = new Atest1();
let funcA = a.getA;
let funcB = a.getB;
funcA();
funcB();
Copy the code
This call is equivalent to window.funca (), so whether the method on the prototype is an arrow function or not. So this is all pointing to widow.
Another way to call it
window.name = 'aaa';
function Atest1(){
this.name = 123;
};
Atest1.prototype={
getA() {
console.log(this.this.name);
return this.name + 1;
},
getB:() = >{
console.log(this);
return this.name + 1; }}let a = new Atest1();
let funcA = a.getA();
Copy the code
This is an obvious call, getA is called from A, so it points to A
Arrow function
In theory an arrow function would point to a if it were a normal function, but in fact it would point to window because it’s an arrow function.
a.getB();
Copy the code
This is an obvious call, getA is called from A, so it points to A
2) (?) The class within this
window.name = 'aaa';
class Atest {
constructor() {
this.name = 123;
}
getA() {
console.log(this);
return this.name + 1;
}
getB=() = >{
console.log(this);
return this.name + 1; }};let a = new Atest();
let funcA = a.getA;
let funcB = a.getB;
funcA();
funcB();
Copy the code
This refers to undefined in class. First, it has nothing to do with super(), which is used in subclasses.
Thanks for your suggestions in the comments section
FunA () is called window.funa () to make this refer to window.
Regular object call
window.name = 'aaa';
class Atest {
constructor() {
this.name = 123;
}
getA() {
console.log(this);
return this.name + 1;
}
getB=() = >{
console.log(this);
return this.name + 1; }};let a = new Atest();
a.getA();
a.getB();
Copy the code
reference
- The front question bank
- The three brothers in Promise.all(),.race(),.allsettled ()
- Promise. AllSettled role
conclusion
The arrow function is timed to bind
This of the outer function
forOwn this
- Each of these functions is one
Individual boxes, each with its own this
.For example, when a function is nested, when a function returns a function, when a function is an argument
.Except that the arrow function is defined when bound to the outer function this
.All the other scenarios look at how the current function is called to determine what this refers to, okay
- Be careful,
Promise constructor
.The location of the resolve ()
.In the Promise constructor
Whether in theResolve before or after
.All with synchronization tasks
To execute.Only then is microtask
. - Note:
Promise to instantiate
The incomingSelf-executing successful or failed callback is not executed
.Callbacks that result in then success and failure are not executed
. Because in theThe Promise implementation is only in the constructor
To perform theResolve or reject
.The state changes. The assignment
. Reject Indicates the failed callback
.The first thing that's going to be caught in then
.And then you get caught in a catch
.If it's captured in then
.Catch will not be in the catch
doubt
- 2) the first paragraph of the code execution is undefined.