我有一些业务逻辑函数要调用,它有一个逻辑必须用到HttpGet,而且要等到结果返回给contiune,如果我用jquery的ajax可以简单的全部做,不知道可观察是不是也有类似的方式?
我希望资源是:
- John
- 安 迪
但现在结果只是显示安迪:(
function main(){
/*
I have more than 70 sharing rules to deal with different Logic
(e.g. getAge , getSomthing...), in order to simplify the problem ,
I only list two rules as a demonstration
*/
methods = [
getNameFromServer,
getSomeOneName
];
const result = [];
methods.forEach(method => {
method(result);
})
console.log(result);
}
function getNameFromServer(result){
Rx.Observable.of('John')
.delay(1000)
.subscribe(name => {
console.log('now async get name , but I need it will be sync')
result.push(name)
});
// can I use sync Ajax like jquery's code?
// $.ajax({
// ... ,
// async: false
// })
// .done(response => result.push(response.xxx))
}
function getSomeOneName(result){
result.push('Andy');
}
// execute
main();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.1/Rx.js"></script>
</head>
<body>
</body>
</html>
在任何现代浏览器中,您可以使用async
/await
来获取同步行为。您必须:
- 将您的
main
声明为async
- 将
forEach
替换为for
..of
(回调不适用于await
( - 将您的
Observable
转换为Promise
以使其可等待,然后将其退回 - 将
subscribe
替换为do
。您仍然会得到副作用,但do
返回可观察量,因此您可以立即链接toPromise
。观察者由toPromise
自动订阅
代码将是:
async function main(){
methods = [
getNameFromServer,
getSomeOneName
];
const result = [];
for (let method of methods) {
await method(result);
}
console.log(result);
}
function getNameFromServer(result){
return Rx.Observable.of('John')
.delay(1000)
.do(name => {
console.log('now async get name , but I need it will be sync')
result.push(name)
})
.toPromise();
// can I use sync Ajax like jquery's code?
// $.ajax({
// ... ,
// async: false
// })
// .done(response => result.push(response.xxx))
}
function getSomeOneName(result){
result.push('Andy');
}
// execute
main();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.1/Rx.js"></script>
</head>
<body>
</body>
</html>