0
1

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 3 years have passed since last update.

【Node.js ☓ Redisをasync/awaitで行う】

Last updated at Posted at 2021-02-02

node-redisとioredisあたりがよく使われているみたい。

redisには型ごとに様々なコマンドがある。
https://www.tutorialspoint.com/redis/index.htm

そのなかでも、結果によって、0 or 1 を返してくれる便利なものもある。

この0 or 1の結果を利用したいときにioredisを使ったほうがasync/awaitを使えるのでネストが深くなったりしなくて済む。

以下では、setnxコマンド(keyがすでに存在していれば→0, なければセットして→1を返す)を例に上げて比べてみる。

node-redisで返り値を取得する方法

const redis = require('redis');
const client = redis.createClient();

client.setnx(['name', name], (err, result) => {
    console.log(result)
		// result = 0 or 1
}

ioredisで返り値を取得する方法

const ioredis = require('ioredis')
const ioclient = ioredis.createClient()
..省略 async () ..
try{
    const result = await ioclient.setnx(['name', name])
    console.log(result)
		// result = 0 or 1
}catch(err){
    console.log(err)
}
..省略

ioredisだとPromiseインスタンスでredisコマンドの結果を返してくれるのでasync/awaitでネストが深くなるのを阻止できる。

試しにawaitを外してみると、Promise { <pending> }が返ってくる。

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?