Example of a simple Javascript Promise mechanism in nodejs, nodejspromise
Promise/deferred is A good specification for processing asynchronous call encoding. The following uses nodejs code as A class to implement A simple implementation of promise/A specifications.
Copy codeThe Code is as follows:
/**
* Created with JetBrains WebStorm.
* User: xuwenmin
* Date: 14-4-1
* Time: AM
* To change this template use File | Settings | File Templates.
*/
Var EventEmitter = require ('events'). EventEmitter;
Var http = require ('http ');
Var util = require ('til ');
// Define the promise object
Var Promise = function (){
// Implement the inherited event class
EventEmitter. call (this );
}
// Inherit the general method of the event
Util. inherits (Promise, EventEmitter );
// The then method is the method in the promise/A specification.
Promise. prototype. then = function (successHandler, errorHandler, progressHandler ){
If (typeof successHandler = 'function '){
This. once ('success ', successHandler );
}
If (typeof errorHandler = 'function '){
This. once ('error', errorHandler );
}
If (typeof progressHandler === 'function '){
This. on ('process', progressHandler );
}
Return this;
}
// Define the latency object
// Contains a state and a promise object
Var Deferred = function (){
This. state = 'unfulfiled ';
This. promise = new Promise ();
}
Deferred. prototype. resolve = function (obj ){
This. state = 'fullfiled ';
This. promise. emit ('success', obj );
}
Deferred. prototype. reject = function (err ){
This. state = 'failed ';
This. promise. emit ('error', err );
}
Deferred. prototype. progress = function (data ){
This. promise. emit ('process', data );
}
// Use an http request to use the promise/deferred defined above
Var client = function (){
Var options = {
Hostname: 'www .baidu.com ',
Port: 80,
Path :'/',
Method: 'get'
};
Var deferred = new Deferred ();
Var req = http. request (options, function (res ){
Res. setEncoding ('utf-8 ');
Var data = '';
Res. on ('data', function (chunk ){
Data + = chunk;
Deferred. progress (chunk );
});
Res. on ('end', function (){
Deferred. resolve (data );
});
});
Req. on ('error', function (err ){
Deferred. reject (err );
})
Req. end ();
Return deferred. promise;
}
Client (). then (function (data ){
Console. log ('request complete', data );
}, Function (err ){
Console. log ('Access error', err );
}, Function (chunk ){
Console. log ('reading ', chunk );
});
Save the code as promise. js. You can run it under the command line and directly enter node promise. js to see the running effect.