magazine off

テクノロジー・マガジン OFFです!コラム ✖️ 最新ニュースをほぼ毎日お届けしています。

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.

 

コメントを残す