Home  >  Article  >  Web Front-end  >  How to call function after nodejs request ends

How to call function after nodejs request ends

PHPz
PHPzOriginal
2023-04-05 13:48:22456browse

In Node.js development, we often need to call a callback function when making an asynchronous request. This callback function is responsible for performing some operations after the request ends. The http module provided by Node.js is a commonly used module for initiating http requests. It can be used for client or server http requests.

In the http module, we usually use the http.get() or http.request() method to initiate http requests. Both methods are asynchronous in that they wait for the request to complete before returning. So how do you call the callback function after the request ends?

Method 1: Pass the callback function as a parameter

In the http.get() method and http.request() method, they both accept a parameter options, which can contain a callback function. This callback function is the function to be executed after the request is completed.

For example, we can use the http.get() method to obtain the content of a web page and output the content to the console after the request is completed:

const http = require('http');

http.get('http://www.example.com', (res) => {
  let data = '';

  // 接收响应数据
  res.on('data', (chunk) => {
    data += chunk;
  });

  // 响应结束时输出结果
  res.on('end', () => {
    console.log(data);
  });
});

In this example, we Send a GET request through the http.get() method to obtain the web page content of http://www.example.com. Then we concatenate the received response data and output it to the console by defining an anonymous function as a callback function.

Method 2: Use Promise object

In addition to passing the callback function as a parameter, we can also use the Promise object to handle operations after the request ends. The Promise object is a new feature in ES6, which is widely used in Node.js asynchronous methods.

In the http module, we can return a Promise object by calling the http.get() or http.request() method. In this Promise object, we can use the then() method to set the function to be executed after the request ends. For example, we can use a Promise object to obtain the content of a web page and output the content to the console after the request is completed:

const http = require('http');

const getRequest = (url) => {
  return new Promise((resolve, reject) => {
    http.get(url, (res) => {
      let data = '';

      // 接收响应数据
      res.on('data', (chunk) => {
        data += chunk;
      });

      // 响应结束时输出结果
      res.on('end', () => {
        resolve(data);
      });
    }).on('error', (err) => {
      reject(err);
    });
  });
};

getRequest('http://www.example.com')
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.error(err);
  });

In this example, we use a function called getRequest() to Returns a Promise object. We wrap the http.get() method in a Promise object and pass the response data to the then() method through the resolve() function at the end of the request. If an error occurs, the error information is passed to the catch() method through the reject() function. Then we output the response data by calling the getRequest() method and defining the then() method in the returned Promise object.

Summary

The above are two methods of initiating http requests in Node.js and calling functions after the request is completed. By passing a callback function as a parameter or using a Promise object, we can perform custom actions after the request ends. In actual development, we can choose the appropriate method to handle asynchronous requests according to the specific situation.

The above is the detailed content of How to call function after nodejs request ends. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn