Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

javascript - 在功能范围之外解决Javascript Promise(Resolve Javascript Promise outside function scope)

I have been using ES6 Promise.(我一直在使用ES6 Promise。)

Ordinarily, a Promise is constructed and used like this(通常,Promise是这样构造和使用的)

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; 
});

And later(然后)

onClick = function(){
    outsideResolve();
}

This works fine, but is there an easier way to do this?(这很好,但是有更简单的方法吗?)

If not, is this a good practice?(如果没有,这是一个好习惯吗?)   ask by Morio translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

simple:(简单:)

var promiseResolve, promiseReject;

var promise = new Promise(function(resolve, reject){
  promiseResolve = resolve;
  promiseReject = reject;
});

promiseResolve();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...