Angular 4 中的 Observable 调用可以像 jquery 的同步 ajax 方式一样吗?



我有一些业务逻辑函数要调用,它有一个逻辑必须用到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>

最新更新