4
2

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.

AWS lambdaで setTimeout を待つ(await, callback2つの手法)

Last updated at Posted at 2020-04-15

lambda で、 setTimeout を利用する場合、何も意識しない場合 lambda の実行が終わってしまいます。

それを待つには、 await を使う方法がパッと思いつきますが、 callback を使っても待つことが出来ます。

await を利用するパターン

Promise を使って書きます。

exports.handler = async (event, context, callback) => {
    await new Promise(resolve => {
        setTimeout(() => {
            console.log('waited!!!!!!!!!!!!')
            resolve();
        }, 2000);
    });
};

callback を利用するパターン

callback メソッドは、実行前に node のイベントループが空になるまで待つようになっているので、 setTimeout が終わるまで待ちます。
( callbackWaitsForEmptyEventLoop がデフォルトだと true なので )
https://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html

exports.handler = async (event, context, callback) => {
    setTimeout(() => {
        console.log('waited!!!!!!!!!!!!')
    }, 2000);
    callback()
};
4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?