处理异步功能的同步方式,两层深 [英] Synchronous way of handling asynchronous function, two level deep
问题描述
我正在遍历一个数组,以使用被调用函数internally calls an asynchronous function
的返回值更新其值.
I am looping over an array to update its values using returned value from called function which internally calls an asynchronous function
.
我需要以同步方式处理异步函数,而异步方法没有被直接调用. 这是复制场景 .
I need to handle asynchronous function in synchronous way which is not being directly called. This is replication of scenario.
function condition(){
// Code of this function is not accessible to me.
return new Promise(function(resolve, reject){
setTimeout(function(){
if(parseInt(Math.random() * 100) % 2){
resolve(true);
}
else{
reject(false)
}
}, 1000)
});
}
async function delayIncrease(value){
var choice = await condition();
if(choice) { return ++value; }
else { return --value; }
}
// Start calling functions
dataArr = [1,2,3,4,5];
for(var i in dataArr){
dataArr[i] = delayIncrease(dataArr[i]);
}
如果可能,我希望采用上述结构的解决方案.
通过adding other function
并将"index" + "new_value"
作为参数传递,我已经达到了预期的结果.此函数直接modifies original array
并产生所需的结果. 工作示例 .
I have achieved the desired result by adding other function
and passing "index" + "new_value"
as parameters. This function directly modifies original array
and produces desired result. Working example.
function condition(){
// Code of this function is not accessible to me.
return new Promise(function(resolve, reject){
setTimeout(function(){
if(parseInt(Math.random() * 100) % 2){
resolve(true);
}
else{
reject(false)
}
}, 1000)
});
}
function delayIncrease(value, index){
condition().then(
function(){ updateData(++value, index) },
function(){ updateData(--value, index) }
)
}
function updateData(value, index){
dataArr[index] = value;
}
dataArr = [1,2,3,4,5];
for(var i in dataArr){
dataArr[i] = delayIncrease(dataArr[i], i);
}
请以最佳方式提供此要求的解决方案.还提出了Angular 4方式的可能解决方案.我想到了以普通JavaScript形式编写它,因为Observables
的行为几乎相同.
Please provide solution for this requirement in best possible way. Possible solution in Angular 4 way is also appriciated. I thought of writing it in normal JavaScript form as Observables
behave nearly same.
我关注了此媒体页和 http://exploringjs.com
推荐答案
您的condition
函数不能真正实现true或false的诺言,而是随机实现或 reject 的诺言.您需要捕获该错误",而不是使用布尔值进行分支:
Your condition
function does not really fulfill the promise with either true or false, it does randomly fulfill or reject the promise. Instead of branching on a boolean, you will need to catch that "error":
async function delayIncrease(value) {
try {
await condition();
return ++value;
} catch(e) {
return --value;
}
}
这篇关于处理异步功能的同步方式,两层深的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!