• [RxJS] Creation operators: from, fromArray, fromPromise


    The of() operator essentially converted a list of arguments to an Observable. Since arrays are often how we structure list of things in JavaScript, we should have a way of transforming arrays into Observables. This lesson teaches how you can convert from Arrays to Observables, from Promises to Observables, and from Iterators to Observables.

    formArray:

    var ary = [1,2,3];
    var foo = Rx.Observable.fromArray(ary);
    
    
    foo.subscribe(function (x) {
      console.log('next ' + x);
    }, function (err) {
      console.log('error ' + err);
    }, function () {
      console.log('done');
    });
    
    /*
    "next 1"
    "next 2"
    "next 3"
    "done"
    */

    fromPromise:

    var prom = fetch('https://null.jsbin.com');
    var foo = Rx.Observable.fromPromise(prom);
    
    foo.subscribe(function (x) {
      console.log('next ' + x.status);
    }, function (err) {
      console.log('error ' + err);
    }, function () {
      console.log('done');
    });
    
    /*
    "next 204"
    "done"
    */

    from:

    from() opreator can create observalbes according to what you passed in

    =fromArray:

    var ary = [1,2,3];
    var foo = Rx.Observable.from(ary);
    
    foo.subscribe(function (x) {
      console.log('next ' + x);
    }, function (err) {
      console.log('error ' + err);
    }, function () {
      console.log('done');
    });
    
    /*
    "next 1"
    "next 2"
    "next 3"
    "done"
    */

    =fromPromiose

    var foo = Rx.Observable.from(prom);
    
    foo.subscribe(function (x) {
      console.log('next ' + x.status);
    }, function (err) {
      console.log('error ' + err);
    }, function () {
      console.log('done');
    });

    From iterator:

    function* generator(){
      yield 10;
      yield 20;
      yield 30;
    }
    
    var iterator = generator();
    var foo = Rx.Observable.from(iterator);
    
    foo.subscribe(function (x) {
      console.log('next ' + x);
    }, function (err) {
      console.log('error ' + err);
    }, function () {
      console.log('done');
    });
    
    /*
    "next 10"
    "next 20"
    "next 30"
    "done"
    */
  • 相关阅读:
    探索Javascript 异步编程
    前端性能调优
    怎样选择前端框架
    前端地图截屏方案
    不一样的山顶角
    前后端分离场景下的另类登录认证方案
    React Diff 算法
    纯css实现Magicline Navigation(下划线动画导航菜单)
    Tinymce group plugin
    自适应process组件
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5389527.html
Copyright © 2020-2023  润新知