Function for checking API status

I'm currently working on an IF statement that will check for results from two API call functions and terminate when it receives results.

function fetchYelp() {
let token = '<token>';
axios.get('https://api.yelp.com/v3/businesses/search?term=Church on the rock&location=saint peters, MO 63376',{
    headers: {
        Authorization: 'Bearer ' + token
    }
})
    .then(res => {
        console.log(res.data);
    })
    .catch(err => {
        console.log(err)
    });

}

fetchYelp();

function fetchWhitePages() {
axios.get('https://proapi.whitepages.com/3.0/business?api_key=<apiKey>&address.city=Saint Peters&address.country_code=US&address.postal_code=63376&name=Church on the rock')
    .then(res => {
        console.log(res.data);
    })
    .catch(err => {
        console.log(err)
    });

}

fetchWhitePages();

I've hit a roadblock.

Answer №1

At the moment, you are not actually returning anything in your code, just logging data when the function is called.

Here is an illustration:

function fetchYelp() {
  let token = '<token>';

    axios.get('https://api.yelp.com/v3/businesses/search?term=Church on the rock&location=saint peters, MO 63376',{
        headers: {
            Authorization: 'Bearer ' + token
        }
    })
    .then(res => {
      if (!res.data) {
        // It is advisable to handle this situation gracefully and return a value indicating no data, as just returning here will exit the function.
        return;
      };

      return res.data
    })
    .catch(err => {
        console.log(err)
    })
};

ESNext using async/await:

async fetchYelp() {
  let token = '<token>';

  try {
    const res = await axios.get('https://api.yelp.com/v3/businesses/search?term=Church on the rock&location=saint peters, MO 63376',{
        headers: {
            Authorization: 'Bearer ' + token
        }
    })

    if (!res.data) {
      // You should still return something here, even if it's just an empty object for demonstration purposes
      return {};
    }

    return res.data
  } catch (err) {
    // The throw statement can also act like a return statement
    throw new Error(err)
  }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Share an encoded image file through Imgur using base64 encoding

http.get('http://path/to/image.jpg', function (res) { var imgData = ''; res.on('data', function (buff) { imgData += buff; }); res.on('end', function () { var imageData = querystring.stringify({ ...

utilize an arrow function as a component prop argument

Struggling to pass the outcome of handleRedirectUrl() function as a prop to ShortUrlField component. In need of assistance, unsure of the mistake I am making const handleRedirectUrl = () => { urlService .getShortenedUrl(urls.slice(-1)[0].shor ...

Issue with setting cookies using res.cookie

Currently, I am in the process of setting up a Node/Express application with a React client for interaction. I have configured passport to manage authentication using JWT. Upon user login, I verify the email and password, then set the cookie: res.cookie(& ...

Detecting repeated keys in a query for a REST connector in loopback

Can anyone help me figure out how to duplicate parameters in a loopback REST connector query? Here's the code snippet I'm working with: details: { 'template': { 'method': 'GET', 'debug': tr ...

Utilize the conditional GET method when including scripts through tags in an HTML webpage

Is it possible to benefit from HTTP conditional requests when including a script in the head section of a page? My goal is to cache dynamically downloaded JavaScript files that are added to the head section using script tags. If this approach isn't fe ...

Setting up an Express.js HTTP proxy server on the local machine with HTTPS capabilities

My goal with Express.js is to achieve a similar result as shown in this image: const app = require("https-localhost")() app.get('/', (req, res) => { console.log(req.originalUrl); // open req.originalUrl in browser }) app.l ...

Securing routes within APIs and clients using next-auth: A comprehensive guide

Managing both the backend and frontend with Express, I have the backend running on port 8080 and the frontend on port 80. /api/route1 responds with a success code 200 and JSON data /api/route2 responds with a success code 200 and JSON data T ...

Instructions on utilizing Tesseract.recognize in Node.js

I am working on developing an OCR program but encountered some issues while declaring the 'Tesseract.recognize' method. Here is the code snippet: const express = require('express'); const fs= require('fs'); const multer = r ...

The npx documentation explicitly states that in order to avoid any conflicts, it is essential to configure all flags and options before specifying any positional arguments. But what exactly does this directive entail?

The official npx documentation explains the differences between using npx and npm exec. npx vs npm exec When utilizing the npx binary, it is crucial to set all flags and options before including any positional arguments. On the other hand, if you run it v ...

Setting up a personalized JSPM registry configuration

I have chosen to use Verdaccio as the platform for hosting a private package. In my current project, I am looking to incorporate this package locally. The package has been successfully published and is now hosted on Verdaccio running on localhost (http://l ...

Guide to securing a MERN application that connects with an external service (Spotify) using OAuth authentication

Currently in the process of developing a MERN stack application that enables users to sign into their Spotify accounts and store data separately from their Spotify library within the app's database. Users can also perform actions on their Spotify acco ...

Tips for managing folders in Gulp

I recently came across a tutorial on CSS-Tricks that caught my interest. The author mentioned the importance of installing node.js, so I followed the instructions and successfully installed it at C:\users\me\AppData\Roaming\npm F ...

NodeJS is throwing a SyntaxError indicating an unexpected token ILLEGAL

After setting up an Ubuntu instance on my university server, I went ahead and installed NodeJS and NPM. With a FTP connection, I was able to send files to the instance. I uploaded the following NodeJS webserver file to my instance and attempted to run it ...

Issue encountered: `node/mysql/nginx` - 502 bad gateway error

My current setup involves running a Node.js application on an Ubuntu server 14.04 with Nginx. I originally had a MySQL database hosted on a different server, but in order to improve performance, I decided to move it to the same server. However, when trying ...

What is the process for adding values to an existing JSON object in MongoDB?

I need to calculate the expenses for a specific category in a particular month. Below is an example of my data stored in MongoDB: { "2022":{ "January":{ "Food":30, "Traveling":0, ...

The html-docs.js generated documentation appears to be empty

Just starting out with node js and learning express js. I'm trying to generate a word file from HTML content using html-docs-js. The issue I'm facing is that the word file is generated in the folder, but it's coming up empty. Here's my ...

Limit access to server-side files from external sources

Our team is currently working on a project using node.js and express.js, but we're not utilizing express-generator to generate the scaffold. Instead, we are creating each folder and file manually. The issue we are facing now is that our server-side co ...

What is the best way to retrieve data from an array within an Express application?

Working with the rest API using express ejs in Node.js has brought up an issue. The JSON data received from the API contains an array within an array. Specifically, I am trying to extract the value of the feature_image attribute under guid. However, when ...

Encountering a 404 not found error in Node.js while attempting to upload a file

Here is the code snippet: angular.module('fileModelDirective',[]) .directive('fileModel',['$parse',function ($parse) { return { restrict: 'A', link: function (scope, element, attrs) { var parsedFile ...

JavaScript - Retrieve a nested property within an object using an array of strings

I possess an object in the following format { metadata: { correlationId: 'b24e9f21-6977-4553-abc7-416f8ed2da2d',   createdDateTime: '2021-06-15T16:46:24.247Z' } } and I possess an array containing the properties I wish to re ...