class Socket {
output(){
return '输出220V';}}
abstract class Power {
abstract charge(): string;}
class PowerAdapter extends Power {
constructor(public socket: Socket){
super();}//转换后的接口和转换前不一样
charge(){
return this.socket.output()+' 经过转换 输出24V';}}
let powerAdapter = new PowerAdapter(new Socket());
console.log(powerAdapter.charge());
//let axios = require('axios');
let url = require('url');
function axios(config: any): any {
let adaptor = getDefaultAdapter();
return adaptor(config);}
axios({
method:'GET',
url:'http://localhost:8080/api/user?id=1'}).then(function (response: any){
console.log(response);}, function (error: any){
console.log(error);})
function xhr(config: any){
return new Promise(function (resolve, reject){
var request = new XMLHttpRequest();
request.open(config.method, config.url,true);
request.onreadystatechange= function (){
if (request.readyState==4){
if (request.status==200){
resolve(request.response);} else {
reject('请求失败');}}}})}
function http(config: any){
let http = require('http');
let urlObject = url.parse(config.url);
return new Promise(function (resolve, reject){
const options ={
hostname: urlObject.hostname,
port: urlObject.port,
path: urlObject.pathname,
method: config.method};
var req = http.request(options, function (res: any){
let chunks: any[]=[];
res.on('data',(chunk: any)=>{
chunks.push(chunk);});
res.on('end',(){
resolve(Buffer.concat(chunks).toString());});});
req.on('error',(err: any)=>{
reject(err);});
req.end();})}
function getDefaultAdapter(): any {
var adapter;
if (typeof XMLHttpRequest !=='undefined'){
adapter = xhr;} else if (typeof process !=='undefined'){
adapter = http;}
return adapter;}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
server.js
let express = require('express');
let app = express();
app.get('/api/user',(req, res)=>{
res.json({ id: req.query.id, name:'zhufeng'});});
app.listen(8080);
let fs = require('fs');
var Bluebird = require("bluebird");
let readFile = Bluebird.promisify(fs.readFile);(async function (){
let content = await readFile('./1.txt','utf8');
console.log(content);})()
1.
2.
3.
4.
5.
6.
7.
8.
function promisify(readFile: any){
return function (filename: any, encoding: any){
return new Promise(function (resolve, reject){
readFile(filename, encoding, function (err: any, data: any){
if (err)
reject(err);
else
resolve(data);})});}}