promise概念:
Promise物件用于表示一個異步操作的最終完成(或失敗)及其結果值,
promise題目:
const first = ()=>(new Promise((resovlve,reject)=>{
console.log(3);
let p = new Promise((resolve,reject)=>{
console.log(7);
setTimeout(()=>{
console.log(5);
resolve(6);
},0);
resolve(1);
});
resolve(2);
p.then(arg =>{
console.log(arg);
});
});
first().then(arg => {
console.log(arg);
});
console.log(4);
//1.同步的代碼 3、7、4
//2.微任務的異步代碼(次高,then)1、2
//3.宏任務的異步代碼(最低)5
//6不執行
//結果:374125
promise 實踐:
【問題分析】
如何把大象放到冰箱
【答題思路】
開門/裝大象/關門 都是異步的操作,
通過本題加強對promise的理解,理解promise解決的核心問題時什么,
console.time()
const openDoor=cb=>{
setTimeout(cb,1000)
}
const putin=cb=>{
setTimeout(cb,3*1000)
}
const closeDoor=cb=>{
setTimeout(cb,1000)
}
const done = () =>{
console.timeEnd();
console.log("done");
}
openDoor(()=>{
putIn(()=>{
closeDoor(()=>{
done();
})
})
})
//用promise解決
const openDoor=()=> new Promise(res=>{
setTimeout(res,1000)
)}
const putin=()=> new Promise(res=>{
setTimeout(res,3*1000)
)}
const closeDoor=()=> new Promise(res=>{
setTimeout(res,1000)
)}
const done = () =>new Promise(res=>{
console.timeEnd();
console.log('done2');
res();
})
openDoor().then(putin).then(closeDoor).then(done)
如何實作鏈式呼叫:
【問題分析】
類似b.then().then().then()的鏈式呼叫是如何實作的?
【答題思路】
因為要不斷的呼叫,所以一定是回傳自己,或者回傳一個和自己類似的結構,后續實作Promise的時候,會用得上!
class Test1{
then(){
console.log(6666);
return this;
}
}
var a = new Test1();
a.then().then().then()
class Test2{
then(){
console.log(77777);
return new Test2();
}
}
var b = new Test2();
b.then().then().then()
promise簡單實作
簡單實作resolve方法和then方法
const State = {
pending:"pending",
resolve:"resolve",
reject:"reject"
}
class MyPromise{
_state = State.pending;
_value;
_resArray = [];
constructor(exclutor){
exclutor(this._resolve.bian(this),this._reject.bind(this))
}
_resolve(val){
this._value = val;
this._state = State.resolve;
this._resArray.forEach(item=>{
item(this._value);
})
}
_reject(){}
then(onRes,onRej = ()=>{}){
this._resArray.push(onRes);
}
}
實作then的鏈式呼叫
const State = {
pending: "pending",
resolved: "resolved",
rejected: "rejected"
};
noop= ()=>{};
class MyPromise{
constructor(exclutor){
exclutor(this._resolve.bind(this),this._reject.bind(this));
}
_state = State.pending;
_value;
_resArray =[];
_resolve(val){
if(this._state === State.pending){
this._value = val;
this._state = State.resolved;
// 執行then 傳入的onRes
this._runResArray();
}
}
_reject() {}
_runResArray(){
this._resArray.forEach(item=>{
const result = item.handle(this._value); //拿到上一個promise的回傳值
const nextPromise = item.promise;
if(result instanceof MyPromise){
result.then(val => item.promise._resolve(val));
}else{
item.promise._resolve(result);
}
})
}
then(onRes,onRej = noop) {
const newPromise = new MyPromise(()=>{});
const item = { promise: newPromise, handle: onRes};
this._resArray.push(item);
if(this._state === State.resolved){
this._runResArray();
}
return newPromise;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/271419.html
標籤:區塊鏈
上一篇:易心傳正|區塊鏈如何作業的?
下一篇:react-腳手架專案搭建