Search code examples
javascriptnode.jses6-promise

Promise related


  1. I am making a travel advisor app. here i have made a getPlacesData function in index.js which fetch data from api return data which i recieve from app.js, i want to know that when i print type of data it gives object, but i know that async function always return promise??

  2. in app.js in useEffect where i have recieve that data there i have also console.log its type it gives object but i know .then return promise.

index.js

// axios is libary which helps us t make  call
import axios from "axios";
const URL =
  "https://travel-advisor.p.rapidapi.com/restaurants/list-in-boundary";
const options = {
  params: {
    bl_latitude: "11.847676",
    tr_latitude: "12.838442",
    bl_longitude: "109.095887",
    tr_longitude: "109.149359",
  },
  headers: {
    "X-RapidAPI-Key": "bb4974756dmsh0ecde312f187eb9p175b1djsn7eeab8063995",
    "X-RapidAPI-Host": "travel-advisor.p.rapidapi.com",
  },
};

export const getPlacesData =  async() => {
  try {

    const { data: { data } } =  await axios.get(URL, options);
    console.log("data:", data);
    console.log("data:", typeof(data));
    return data;//returns restaurant data

  } 
  catch (error) {

    console.log(error);

  }
};

app.js


import React,{useState,useEffect} from "react";
import { CssBaseline, Grid } from "@material-ui/core";
import { getPlacesData } from "./api";
import Header from "./components/Header/Header";
import List from "./components/List/List";
import Map from "./components/Map/Map";
import PlaceDetails from "./components/PlaceDetails/PlaceDetails";

const App = () => {
  const [places,setPlaces]=useState([]);
  useEffect(()=>{
    getPlacesData()
    .then((data)=>{//we use .then because getPlacesData is async
      console.log("appdata",data);
      console.log("appdata:", typeof(data));
      setPlaces(data);
    })
  },[])
  return (
    <>
      <CssBaseline />
      <Header />
      <Grid container spacing={3} style={{ width: "100%" }}>
        <Grid item xs={12} md={4}>
          <List />

        </Grid>
        <Grid item xs={12} md={8}>
          <Map />

        </Grid>
      </Grid>
    </>
  );
};

export default App;

I want to get rid of my confusion.


Solution

  • .then() method of a Promise is called once the promise has been resolved. If the promise is rejected then the first chained catch() clause is executed.

    Hence in you case you will always receive an resolved value i.e an object from api response.

    async function someTask() {
      return new Promise((resolve, reject) => {
        setTimeout(() => resolve(1), 2000);
      })
    }
    
    async function someOtherTask() {
      return new Promise((resolve, reject) => {
        setTimeout(() => reject(0), 2500);
      })
    }
    
    
    
    someTask().then((val) => console.info('in then '+val))
    someOtherTask().then((val) => console.log(val)).catch(err => console.info('in catch: ' + err));