Promiseで非同期処理をするメモ

非同期処理の書き方色々

myAsync.js

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
'use strict';
// Promiseオブジェクトをそのまま返す
let readAsync = new Promise(function (resolve, reject) {
fs.readFile('./README.md', function (err, data) {
resolve(data);
})
});
// Promiseオブジェクトを返す関数
let writeAsync = function (data) {
return new Promise(function (resolve, reject) {
fs.writeFile('./README-copy.md', data, function (err) {
resolve();
});
});
}
// Defferedオブジェクトのpromiseを返す
let renameAsync = function () {
var d = Promise.defer();
fs.rename('./README-copy.md', './README-copy-modified.md', function (err) {
d.resolve();
});
return d.promise;
};
// Generator
let AppendAsync = function* (){
fs.appendFile('./README-copy-modified.md', 'this string is appended.');
yield;
};
readAsync
.then(writeAsync)
.then(renameAsync)
.then(function () {
AppendAsync().next();
});

実行してみる

1
babel-node myAsync.js