解析函数范围外的 Javascript Promise [英] Resolve Javascript Promise outside function scope
本文介绍了解析函数范围外的 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?
推荐答案
简单:
var promiseResolve, promiseReject;
var promise = new Promise(function(resolve, reject){
promiseResolve = resolve;
promiseReject = reject;
});
promiseResolve();
这篇关于解析函数范围外的 Javascript Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文