Javascript 避免承诺构造函数反模式:我如何拒绝?
而不是像这样编写我的函数:Javascript 避免承诺构造函数反模式:我如何拒绝?,javascript,es6-promise,Javascript,Es6 Promise,而不是像这样编写我的函数: const clearContent = (animation = Promise.resolve()) => { return new Promise((resolve, reject) => { const child = $('#child'); animation.then(animationEvent => { const eventPackage = { 'divRemoved'
const clearContent = (animation = Promise.resolve()) => {
return new Promise((resolve, reject) => {
const child = $('#child');
animation.then(animationEvent => {
const eventPackage = {
'divRemoved': 'divIDPlaceholder',
'itemRemoved': 'contentIDPlaceholder',
'remainingItemsCount': 2,
'remainingItems': 1
};
child.remove();
const contentRemovedEvent = new CustomEvent('contentRemovedFromPlaceholder', {
'detail': eventPackage
});
window.dispatchEvent(contentRemovedEvent);
console.log('Removed!');
return resolve(eventPackage);
});
});
}
我想我现在知道了如何在不引入不必要的复杂性的情况下编写它们。我避免创建新的承诺
,因为它们本质上是可以的:
const clearContent = (animation = Promise.resolve()) => {
const child = $('#child');
return animation.then(animationEvent => {
const eventPackage = {
'divRemoved': 'divIDPlaceholder',
'itemRemoved': 'contentIDPlaceholder',
'remainingItemsCount': 2,
'remainingItems': 1
};
child.remove();
const contentRemovedEvent = new CustomEvent('contentRemovedFromPlaceholder', {
'detail': eventPackage
});
window.dispatchEvent(contentRemovedEvent);
console.log('Removed!');
return eventPackage;
});
}
在动画中发生的任何事情。然后(()…
会影响动画
的承诺。它将无法解决,除非在这里发生的任何事情也无法“解决”,这就是我的问题
如果
return
是一切正常的信号,那么计数器是什么?我如何告诉animation
不要解决?所说的“不要解决”,你的意思是“拒绝”?你可以通过抛出异常,或者返回另一个被拒绝的承诺来实现。你可以抛出新的错误(…)
然后.catch()
它就在promise.Correct上。取而代之的是拒绝。同样地,只是为了确认,当时依赖于clearContent
的函数如果使用throw
的话,解析/拒绝
现在将命中它的拒绝
?是的----------也请参见“不解析”,你的意思是“改为拒绝”?您可以通过抛出一个异常,或返回另一个被拒绝的承诺来执行此操作。您可以抛出新错误(…)
,然后.catch()
将其放在promise.Correct上。改为拒绝“。因此,仅需确认,如果使用了throw
,则依赖于clearContent
的resolve/reject
功能现在将命中它的reject
?是----------另请参见