19
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

util.promisify()でcallbackスタイルの関数をpromise化

Last updated at Posted at 2017-06-14

util.promisify()でcallbackスタイルの関数をpromise化

node.jsがv8になり、util.promisifyが追加されました。
この機能は、callbackスタイルをpromiseに変換する機能となります。
以下で、試して見たいと思います。

注意事項

  • node.jsのcallbackスタイルの関数であること。(error, value) => ...(calback関数の最初の引数はerrorである必要があります。)
  • callbackを最後の引数としていること。

util.promisify()を試す

以下の処理は、カレントディレクトリにあるtext.txtを出力するだけの処理です。
その中で、fs.readFileをutil.promisifyでpromiseに変換した上で、async/awaitを使用して同期処理の様に扱っています。

'use strct';

const fs = require('fs');
const util = require('util');

const readFileAsync = util.promisify(fs.readFile);

const filePath = './test.txt';

async function promisifyTest() {
    try {
        const text = await readFileAsync(filePath, {encoding : 'utf8'});
        console.log(text);
    } catch (error) {
        console.log(error);
    }
}

promisifyTest();

参考

Node.js v8.1.1 Documentation

19
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?