lux*_*lux 3 javascript es6-promise
使用Angular时,我通常使用JQuery的$.Deferred对象来即时创建promise.除了实际的HTTP请求之外,它非常适合在promise中返回任意模拟数据:
getMockData: function() {
var deferred = $.Deferred();
deferred.resolve({mockData: 'foo-bar'});
return deferred.promise();
}
Run Code Online (Sandbox Code Playgroud)
很简单.也就是说,我现在正在使用Aurelia,它与Angular没有绑定到JQuery(或jqLite).因此,我输了$.Deferred().是否有类似的库可以提供相同的功能$.Deferred()?
否则,只是安装JQuery并$.Deferred()在必要时使用它被认为是不恰当或不好的做法?我怀疑它只是暂时的,但也许不是.我不反对JQuery,但显然不想导入它只是为了获得单个模块.
Aurelia示例:
import {DataService} from './data-service';
import {inject} from 'aurelia-framework';
@inject(DataService)
export class PatientService {
constructor(dataService) {
this.dataService = dataService;
}
getPatients(url, emr) {
// Server incomplete, so comment out the real call (for now)
// return this.dataService.get(url + '/patients?emr=' + emr);
[generate and return a promise here. Cool to just use $.Deferred()?]
}
}
Run Code Online (Sandbox Code Playgroud)
getPatients(url, emr) {
// Server incomplete, so comment out the real call (for now)
// return this.dataService.get(url + '/patients?emr=' + emr);
return new Promise((resolve) => resolve({mockData: 'foo-bar'}));
// or
// return Promise.resolve({mockData: 'foo-bar'});
}
Run Code Online (Sandbox Code Playgroud)
一旦适当的承诺实现已经存在,那么不应该回到jQuery范围之外的Deferred(反)模式.
dataService 如果不断需要,可以在内部进行模拟.
| 归档时间: |
|
| 查看次数: |
138 次 |
| 最近记录: |