Open EdwardZZZ opened 7 years ago
华叔,看了好久终于看懂了,但是有个小bug
new Promise((resolve, reject) => {
setTimeout(function() {
resolve('hhh2')
}, 1000);
}).then((data) => {
console.log(data);
return new Promise((resolve, reject) => {
setTimeout(function() {
reject('ddd2');
}, 1000);
})
}).catch((data) => {
console.log(data);
});
用例通不过,换成newValue.then(resolve, reject);
就好了。
或者直接把
if (newValue.status === REJECTED) {
newValue.catch(reject);
} else {
newValue.then(resolve, reject);
}
整个换成newValue.then(resolve, reject);
是不也行?
@ynchuan 哈哈,之前写的有问题,被你发现啦。 确实可以用 newValue.then(resolve, reject); 就行,因为状态不同的时候会自动找对应的方法执行。
const req = (str, fn) => {
const time = Math.random() * 3e3;
setTimeout(() => {
if (time > 2e3) return fn(new Error(`time too long, ${str}, ${time}`));
fn(null, `${str},${time}`);
}, time);
}
const reqP = (str) => new Promise((resolve, reject) => {
req(str, (err, _str) => {
if (err) return reject(err);
resolve(_str);
});
});
let reqN = 0;
const waitPool = [];
function r(...props) {
return new Promise((resolve, reject) => {
const pThen = async (props1, resolve1, reject1) => {
try {
const data = await reqP(...props1);
resolve1(data);
} catch (err) {
reject1(err);
} finally {
reqN--;
if (waitPool.length > 0) {
const { props: props2, resolve: resolve2, reject: reject2 } = waitPool.shift();
reqN++;
pThen(props2, resolve2, reject2);
}
}
}
if (reqN < 3) {
reqN++
pThen(props, resolve, reject);
} else {
waitPool.push({ props, resolve, reject });
}
});
}
r('a').then(str => console.log(str)).catch(err => console.log(err.message));
r('b').then(str => console.log(str)).catch(err => console.log(err.message));
r('c').then(str => console.log(str)).catch(err => console.log(err.message));
r('d').then(str => console.log(str)).catch(err => console.log(err.message));
r('e').then(str => console.log(str)).catch(err => console.log(err.message));
r('f').then(str => console.log(str)).catch(err => console.log(err.message));
r('g').then(str => console.log(str)).catch(err => console.log(err.message));
r('h').then(str => console.log(str)).catch(err => console.log(err.message));
r('i').then(str => console.log(str)).catch(err => console.log(err.message));
const p = () => new Promise((_, reject) => setTimeout(reject, 3e3));
(async () => {
let i = 'a';
try {
i = await p().catch(err => {});
console.log(1, i);
} catch (err) {
console.log(2, i);
}
})();
function test() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error(123));
}, 1000);
});
}
(async () => {
await test().catch(err => {
console.log(err);
})
console.log(123);
})();
链式
队列