Skip to content

Instantly share code, notes, and snippets.

@haiiro-shimeji
Last active April 22, 2017 07:59
Show Gist options
  • Save haiiro-shimeji/f738364da6ddfb9695f6a6ec80aba839 to your computer and use it in GitHub Desktop.
Save haiiro-shimeji/f738364da6ddfb9695f6a6ec80aba839 to your computer and use it in GitHub Desktop.
Javascript asynchronous sample
//Dummy resource
module.exports = {
open: function() {
var res = {
read: function() {
return new Promise(function(_resolve, _reject) {
setTimeout(function() {
_resolve('hogeeee');
//return _reject('read error!');
}, 1000);
});
},
close: function() {
console.log('Resource is closed.');
}
};
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log('Resource is opened.');
return resolve(res);
//reject('open error!');
}, 1000);
});
}
};
//since ES7 or NodeJS 7
var Resource = require('./00. Resource');
(async ()=> {
const res = await Resource.open("path");
try{
const result = await res.read();
console.log(result);
}
finally{
res.close();
}
})().catch((err)=> console.error((err&&err.stack) || err));
const Resource = require('./00. Resource');
(function() {
//Open resource.
var res = Resource.open('path');
//Read content from resource.
var result = res.then(function(_res) { return _res.read(); });
//Print result.
result.then(function(_result) {
console.log(_result);
});
//Close resource.
Promise.all([res, result])
.then(
function() {
res.then(function(_res) { _res.close(); });
},
function() {
res.then(function(_res) { _res.close(); });
}
);
//Print error.
Promise.all([res, result]).catch(function(err) {
console.error(err);
});
})();
var Resource = require('./00. Resource');
var co = require('co');
co(function* () {
var res = yield Resource.open('path');
try {
var result = yield res.read();
console.log(result);
} finally {
res.close();
}
})
.catch(function(err) { console.error(err); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment