在功能范围之外解决Javascript Promise [英] Resolve Javascript Promise outside function scope

查看:108
本文介绍了在功能范围之外解决Javascript Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用ES6 Promise。

I have been using ES6 Promise.

通常,Promise的构造和使用就像这样

Ordinarily, a Promise is constructed and used like this

new Promise(function(resolve, reject){
    if (someCondition){
        resolve();
    } else {
        reject();
    } 
});

但为了灵活性,我一直在做类似下面的事情来解决问题。

But I have been doing something like below to take the resolve outside for the sake of flexibility.

var outsideResolve;
var outsideReject;
new Promise(function(resolve, reject) { 
    outsideResolve = resolve; 
    outsideReject = reject; 
});

以后

onClick = function(){
    outsideResolve();
}

这种方法很好,但是有更简单的方法吗?如果没有,这是一个好习惯吗?

This works fine, but is there an easier way to do this? If not, is this a good practice?

推荐答案

不,没有其他方法可以做到这一点 - 我唯一可以说的是这个用例不是很普通的。就像Felix在评论中所说的那样 - 你所做的将会一直有效。

No, there is no other way to do this - the only thing I can say is that this use case isn't very common. Like Felix said in the comment - what you do will consistently work.

值得一提的是,promise构造函数的行为方式就是抛出安全 - 如果你做了一个例外当你的代码在promise构造函数中运行时,预期不会发生,它会变成拒绝,这种抛出安全形式 - 将抛出的错误转换为拒绝是很重要的,有助于维护可预测的代码。

It's worth mentioning that the reason the promise constructor behaves this way is throw safety - if an exception you did not anticipate happens while your code is running inside the promise constructor it will turn into a rejection, this form of throw safety - converting thrown errors to rejections is important and helps maintain predictable code.

对于这个抛出安全的原因,promise构造函数被选择为延迟(这是一种替代的承诺构造方式,允许你正在做的事情) - 至于最佳实践 - 我将传递元素并使用promise构造函数相反:

For this throw safety reason, the promise constructor was chosen over deferreds (which are an alternative promise construction way that do allow what you're doing) - as for best practices - I'd pass the element and use the promise constructor instead:

var p = new Promise(function(resolve, reject){
    this.onclick = resolve;
}.bind(this));

出于这个原因 - 只要你可以使用promise构造函数而不是导出功能 - 我建议你使用它。每当你可以避免两者 - 避免两者和链。

For this reason - whenever you can use the promise constructor over exporting the functions - I recommend you do use it. Whenever you can avoid both - avoid both and chain.

注意,你不应该使用promise构造函数来处理 if(condition),第一个例子可以写成:

Note, that you should never use the promise constructor for things like if(condition), the first example could be written as:

var p = Promise[(someCondition)?"resolve":"reject"]();

这篇关于在功能范围之外解决Javascript Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆