我正在尝试为fileupload功能创建包装器模块。 下面的代码看起来适用于我的场景,最近我遇到了rxjs,并想知道我如何将下面的方法转换为Observable。什么比承诺更有优势。
```
// 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"
});
答案 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 => ...)