Help us understand the problem. What is going on with this article?

DynamoDBでPromiseが使えた(Lambda Node.js)

はじめに

Lambda(Node.js)でDynamoDBに接続し、値を取得したいときに、
非同期であるために、自分でPromiseで返す関数を作成していた。

コード

/**
 * データの挿入を行う。
 * @param ddb
 * @param params
 * @returns {Promise<any>}
 */
exports.addItem = function (ddb, params) {
    return new Promise(function (resolve) {
        ddb.putItem(params, function (err, data) {
            if (err) {
                console.log("PUT失敗", err, err.stack);
            } else {
                console.log("PUT成功");
                resolve(data);
            }
        });
    });
};

await this.addItem(ddb, putParams);

改善後

なんと最後にpromise()を呼ぶことで、Promise型のものを返却してくれるようで、わざわざ自分でラップする必要がなかった。

await ddb.getItem(findParams, function (err, data) {
            if (err) {
                console.log("GET失敗");
            } else {
                console.log("GET成功");
            }
        }).promise();
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした