Promise 가 뭐야?하나의 Promise 를 실현 하 다.
2. promise 란 무엇 인가?
//
const geilaopomaibao = new Promise((resolve, reject) => {
//
if (money) {
//
reslove('10k');
} else {
//
reject(' , ');
}
})
// , 。
geilaopomaibao.then(
res => {
// res
maibao(res);
},
reason => {
//
// reason
}
);
- :
```
const task = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(' ');
}, 3000);
})
task.then((res) => {
// 3
console.log(res);
})
```
, callback resolve,
```
// , ,then
new Promise((resolve, reject) => {
$.ajax('/api/user/login', {
success: function(isLogin) {
if (isLogin) {
resolve(data);
} else {
reject(' ');
}
}
})
}).then(
res => {
$.ajax('/api/list', {
success: function(data) {
resolve(data);
}
})
},
reason => {
alert(reason)
}
).then((data) => {
// data list
// list
return data.sort();
}).then((list) => {
// , list
})
```
- promise , ;
1. Promise.all() ( promise , , )
```
const task1 = {ji: 2018};
const task2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('2018 ');
}, 5000);
});
const task3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(' ');
}, 2000);
});
Promise.all([task1, task2, task3]).then(values => {
console.log(values);
// 5 [{ji: 2018}, '2018 ', ' ']
});
```
2. Promise.race() ( promise , , promise )
```
const task2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('2018 ');
}, 5000);
}); ;
const task3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(' ');
}, 2000);
});
Promise.race([task1, task2, task3]).then(values => {
console.log(values);
// 2 ' '
});
```
3. Promise.resolve() ( , promise, : promise, , )
```
/**
* @param {Promise} fn promise
*/
const task = (fn) => {
fn.then()
// ........
}
Promise.resolve(1);
```
4. Promise. reject() ( , promise)
4. 하나의 promise 실현
class Promise {
constructor(task) {
// { pending fulfilled rejected } 3
this.status = 'pending';
// resolve
this.resolveData = null;
// reject
this.rejectData = null;
//
this.onFulfilledList = [];
this.onRejectedList = [];
//
try {
task(this.onResolve.bind(this), this.onReject.bind(this));
} catch (e) {
this.onReject(e);
}
}
/**
* ,
*
* @param {any} data resolve
*/
onResolve(data) {
if (this.status === 'pending') {
this.status = 'fulfilled';
this.resolveData = data;
this.onFulfilledList.forEach(fn => {
fn(this.resolveData);
})
}
}
/**
* ,
*
* @param {any} data reject
*/
onReject(data) {
if (this.status === 'pending') {
this.status = 'rejected';
this.rejectData = data;
this.onRejectedList.forEach(fn => {
fn(this.rejectData);
})
}
}
/**
*
*
* @param {function} onFulfilled
* @param {function} onRejected
* @return {*}
*/
then(onFulfilled, onRejected) {
if (typeof onFulfilled !== 'function') {
onFulfilled = () => {};
}
if (typeof onRejected !== 'function') {
onRejected = () => {};
}
let promise2;
switch (this.status) {
case 'pending':
promise2 = new Promise((resolve,reject) => {
this.onFulfilledList.push(() => {
let x = onFulfilled(this.resolveData);
this.resolvePromise(promise2, x, resolve, reject);
});
this.onRejectedList.push(() => {
let x = onRejected(this.rejectData);
this.resolvePromise(promise2, x, resolve, reject);
});
});
break;
case 'fulfilled':
promise2 = new Promise((resolve, reject) => {
let x = onFulfilled(this.resolveData);
this.resolvePromise(promise2, x, resolve, reject);
});
break;
case 'rejected':
promise2 = new Promise((resolve, reject) => {
let x = onRejected(this.rejectData);
this.resolvePromise(promise2, x, resolve, reject);
});
break;
default:
throw 'promise status error';
}
return promise2;
}
/**
* catch reject
*
* @param onRejected
*/
catch(onRejected) {
if (typeof onRejected !== 'function') {
onRejected = () => {};
}
let promise2;
promise2 = new Promise((resolve, reject) => {
let x = onRejected(this.rejectData);
this.resolvePromise(promise2, x, resolve, reject);
});
}
/**
* , then
*
* @param {Promise} promise2 promise
* @param {any} x then
* @param {function} resolve
* @param {function} reject
* @return {*}
*/
resolvePromise(promise2, x, resolve, reject) {
// then
let then;
// x promise2
if(promise2 === x){
return reject(new TypeError(' '));
}
if (x instanceof Promise) {
if(x.status === 'pending'){
x.then(function(y){
resolvePromise(promise2, y, resolve, reject);
}, reject);
} else if (x.status === 'fulfilled'){
resolve(x.resolveData);
} else if (x.status === 'rejected'){
reject(x.rejectData);
}
} else if (x != null && (typeof x === 'object' || typeof x === 'function')) {
try {
// then
then = x.then;
// then fn then
if (typeof then == 'function') {
then.call(x, function (y) {
resolvePromise(promise2, y, resolve, reject)
}, reject);
} else {
// then fn x fulfill promise
resolve(x);
}
} catch (e) {
reject(e);
};
} else {
resolve(x);
}
}
/**
* all , promise
* 1. reject, reject
*
* @param {Array} promiseList
* @return {Promise}
*/
static all(promiseList) {
// ,
if (!Array.isArray(promiseList)) {
new TypeError('must be an array');
}
return new Promise((resolve, reject) => {
// 0 resolve
if (promiseList.length === 0) {
resolve([]);
}
const allData = new Array();
let resI = 0;
promiseList.forEach((item, index) => {
if (item instanceof Promise) {
item.then(
res => {
allData[index] = res;
resolveAll();
},
rej => {
reject(rej);
}
)
} else {
allData[index] = item;
resolveAll();
}
})
function resolveAll() {
resI++;
if (resI === promiseList.length) {
resolve(allData);
}
}
});
}
/**
* race promise ,
*
* @param {Array} promiseList
* @return {Promise}
*/
static race(promiseList) {
// ,
if (!Array.isArray(promiseList)) {
new TypeError('must be an array');
}
return new Promise((resolve, reject) => {
// 0 resolve
if (promiseList.length === 0) {
resolve([]);
}
promiseList.forEach(item => {
promiseList.forEach(item => {
if (item instanceof Promise) {
item.then(
res => {
resolve(res);
},
rej => {
reject(rej);
}
)
} else {
resolve(item);
}
})
})
})
}
/**
* resolve
*
* @param value
* @return {Promise}
*/
static resolve(value) {
return new Promise((resolve, reject) => {
if (value instanceof Promise) {
value.then(res => {
resolve(res);
})
} else {
resolve(value);
}
})
}
/**
* reject
*
* @param reason
* @return {Promise}
*/
static reject(reason) {
return new Promise((resolve, reject) => {
reject(reason);
})
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.