Fer*_*ito 0 javascript asynchronous async-await ecmascript-6 es6-promise
以下情况:
function myFunction() {
return new Promise(function (resolve, reject) {
doSomething();
let myVariable = doSomethingElse();
let otherVariable = doOtherThings(myVariable);
return resolve(otherVariable);
});
}
Run Code Online (Sandbox Code Playgroud)
现在,我希望myVariable不是通过函数调用初始化,而是在回调中,或者更确切地说,在.then异步函数返回的promise中.
function myFunction() {
return new Promise(function (resolve, reject) {
doSomething();
let myVariable;
asynchronousFunctionThatReturnsPromise().then(function(param) {
myVariable = doSomethingElse(param);
});
let otherVariable = doOtherThings(myVariable);
return resolve(otherVariable);
});
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,外部函数会等到myVariable被赋值,直到它执行doOtherThings(myVariable),但我想这在javascript中是不可能的.
不幸的是,我不能简单地将所有以下代码放在"回调"函数中,因为外部函数返回依赖于结果.
有没有办法可以处理这个问题,理想情况下无需更改外部函数(myFunction)上的任何内容?
完全摆脱承诺包装.这是一种承诺反模式,将一个承诺包装在另一个承诺周围.相反,只需返回已有的那个并将逻辑放在.then()处理程序中:
function myFunction() {
doSomething();
return asynchronousFunctionThatReturnsPromise().then(function(param) {
let myVariable = doSomethingElse(param);
let otherVariable = doOtherThings(myVariable);
return otherVariable;
});
});
}
Run Code Online (Sandbox Code Playgroud)
用法:
myFunction().then(val => {
console.log(val); // will be the value of otherVariable above
}).catch(err => {
console.log(err);
});
Run Code Online (Sandbox Code Playgroud)
不幸的是,我不能简单地将所有以下代码放在"回调"函数中,因为外部函数返回依赖于结果.
目前尚不清楚这意味着什么.您必须更改外部函数才能myFunction()正确写入.
有没有办法可以处理这个问题,理想情况下无需更改外部函数(myFunction)上的任何内容?
不.您应该修改myFunction以正确编写代码.如果你有一些现实世界的情况,有一些现实世界的限制,那么你必须发布一个不同的问题,包括那些实际细节和真实代码(不是伪代码),以便我们更具体地为你提供建议.