Rxjs是承诺方法的替代方案

时间:2016-09-25 02:35:20

标签: node.js promise rxjs rxjs5

我正在尝试为fileupload功能创建包装器模块。 下面的代码看起来适用于我的场景,最近我遇到了rxjs,并想知道我如何将下面的方法转换为Observable。什么比承诺更有优势。

http://mono.software/2014/07/07/Creating-NodeJS-modules-with-both-promise-and-callback-API-support-using-Q/

```

// dual-module.js
var Q = require('q');

module.exports = {
  getFullName: function (firstName, lastName, callback) {
    var deferred = Q.defer();

    if (firstName && lastName) {
        var fullName = firstName + " " + lastName;
        deferred.resolve(fullName);
    }
    else {
        deferred.reject("First and last name must be passed.");
    }

    deferred.promise.nodeify(callback);
    return deferred.promise;
 }
}

```

var DualModule = require('dual-module');

DualModule.getFullName("John", "Doe")
.then(function (result) {
    // result returns "John Doe"
})
.fail(function (error) {
    // error returns error message if either first or last name are null or undefined
});


var DualModule = require('dual-module');

DualModule.getFullName("John", "Doe", function (error, result) {
    // error returns error message if either first or last name are null or undefined   
    // result returns "John Doe"
});

1 个答案:

答案 0 :(得分:1)

使用本机Promise和RxJS fromPromise

let promise = new Promise((resolve, reject) => {
  if xxx resolve(yyy)
  else reject(zzz)
})

let stream$ = Rx.Observable.fromPromise(promise)
  .map(res => ...)
  .catch(err => ...)