node.js | Writing a thing that executes process B after process A is done.

Not only in node.js, but also when writing asynchronous processing, there are times when the process does not run in order from the top, but the next process runs with the variable undefined.

 

In order to solve this problem, we need to write a callback or something like that, and when process A returns, process B will be executed.

 

Well, there is plenty of information on this kind of detail, so I’m just writing this article as a reminder.

 

The code I wrote looks like this.

 

.
    async function A() {
      try {
        // Asynchronous processing by awaiting in this case.
         return "return value";
      } catch (err) { 
        console.log("Error occurred");
        console.log(err);
      }
    }

.
It looks like this: hit api or something in try, and return when you receive it.

.
    A().then(result => {
      console.log("Trigger B when A process is returned"); 
      B(result)
    });

.
result is the value returned by executing A().

 

This prevents asynchronous processing from proceeding undefined when written normally.

 

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です