How do I return an item from an async funtion - javascript

Ive been looking into trying to get information from websites using fetch. Trying async/await was my first solution, and so far it has been going well. Getting the information I needed was a breeze, but trying to retrieve that data in main is my problem. Const data in my main function even with the await tag only returns an undefined object. How can I get the data that I have in the function into my main
import React from "react";
import {
WASTEMANAGEMENT_USERNAME,
WASTEMANAGEMENT_PASSWORD,
WASTEMANAGEMENT_APIKEY_AUTH,
WASTEMANAGEMENT_APIKEY_CUSTID,
WASTEMANAGEMENT_APIKEY_DATA,
} from "#env";
async function login() {
let response = await fetch("https://rest-api.wm.com/user/authenticate", {
method: "POST",
headers: {
"content-type": "application/json",
apikey: WASTEMANAGEMENT_APIKEY_AUTH,
},
body: JSON.stringify({
username: WASTEMANAGEMENT_USERNAME,
password: WASTEMANAGEMENT_PASSWORD,
locale: "en_US",
}),
});
let res = await response.json();
const id = res.data.id;
const access_token = res.data.access_token;
response = await fetch(
`https://rest-api.wm.com/authorize/user/${id}/accounts?lang=en_US`,
{
method: "GET",
headers: {
oktatoken: access_token,
apikey: WASTEMANAGEMENT_APIKEY_CUSTID,
},
}
);
res = await response.json();
const custId = res.data.linkedAccounts[0].custAccountId;
response = await fetch(
`https://rest-api.wm.com/account/${custId}/invoice?userId=${id}`,
{
method: "GET",
headers: {
apikey: WASTEMANAGEMENT_APIKEY_DATA,
token: access_token,
},
}
);
res = await response.json();
res.body.balances.filter((item) => {
if (item.type === "Current") {
console.log(item);
return item;
}
});
}
const WasteManagementLogin = async () => {
const data = await login();
console.log(data);
};
export default WasteManagementLogin;

Related

Unable to invoke "btoa" and "item.slice" method in my script for retrieving the playlist

Whenever I am trying to invoke the "btoa" method, I am not able to use this within my script. I created a variable to store the client id: client_secret in base64. The id and secrets are being retrieved from the ".env" file.
I have also tried to use the Buffer method, but unable to use this as well. I am getting the error "invalid from" in Buffer.
can someone help me?
Please look at the full code,
const client_id = process.env.SPOTIFY_CLIENT_ID;
const client_secret = process.env.SPOTIFY_CLIENT_SECRET;
const refresh_token = process.env.SPOTIFY_REFRESH_TOKEN;
const basic = btoa(`${client_id}:${client_secret}`);
const NOW_PLAYING_ENDPOINT = `https://api.spotify.com/v1/me/player/currently-playing`;
const TOP_TRACKS_ENDPOINT = `https://api.spotify.com/v1/me/top/tracks`;
const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`;
const getAccessToken = async () => {
const response = await fetch(TOKEN_ENDPOINT, {
method: 'POST',
headers: {
Authorization: `Basic ${basic}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token
})
});
return response.json();
};
export const getNowPlaying = async () => {
const { access_token } = await getAccessToken();
return fetch(NOW_PLAYING_ENDPOINT, {
headers: {
Authorization: `Bearer ${access_token}`
}
});
};
export const getTopTracks = async () => {
const { access_token } = await getAccessToken();
return fetch(TOP_TRACKS_ENDPOINT, {
headers: {
Authorization: `Bearer ${access_token}`
}
});
};
Using the above script I am trying to embed the customized Spotify play on my site. This wrapper is intended to display the top track as well.
Also, whenever I am trying to run the wrapper used to display the top tracks, it displays the following error,
Full code for displaying the top tracks:
import { type NextRequest } from 'next/server';
import { getTopTracks } from 'lib/spotify';
export const config = {
runtime: 'experimental-edge'
};
export default async function handler(req: NextRequest) {
const response = await getTopTracks();
const { items } = await response.json();
const tracks = items.slice(0, 10).map((track) => ({
artist: track.artists.map((_artist) => _artist.name).join(', '),
songUrl: track.external_urls.spotify,
title: track.name
}));
return new Response(JSON.stringify({ tracks }), {
status: 200,
headers: {
'content-type': 'application/json',
'cache-control': 'public, s-maxage=86400, stale-while-revalidate=43200'
}
});
}
The problem is that you misspelled the Bytes to ASCII function, it is btoa, not btao.
If you are looking to do it the other way around, spell it atob.

POST returns undefined with Cloud Function

I'm implementing Stripe for React Native and I'm trying to send the customerId to my Cloud Function using POST, but when I execute the code it returns in the console.log undefined
Cloud Function (Firebase)
exports.addCardForExistingCustomer = functions.https.onRequest(async (request, response) => {
let id = await request.body.customer_id
response.send({
result: id
})
});
Client side
const fetchPaymentSheetParams = async () => {
const response = await fetch(`${API_URL}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ customer_id: customerId })
});
const { result } = await response.json();
console.log(result)
};

calling variable outside the function

I'm trying to develop a web page that get the data from another web application using axios.get and I wanna insert this data into the Postgres database, the problem is data is inside the then promise, I can not access it to insert it to the database, how can I do that or how can I access the data outside the then
I wanna insert var rn0 ty0
this is the main.js
const axios = require('axios')
const InsertToDataBase = require("./InsertToDataBase");
const username = 'admin'
const password = 'admin'
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')
const urlLAMP_0 = 'http://127.0.0.1:8282/~/mn-cse/mn-name/LAMP_0/DATA/la'
const urlLAMP_1 = 'http://localhost:8282/~/mn-cse/mn-name/LAMP_1/DATA/la'
function getDataLAMP_0(){
axios.get(urlLAMP_0, {
headers: {
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Origin':'*',
"X-M2M-RI":"OM2M-webpage",
'Authorization': `Basic ${token}`,
'Accept': 'application/json',
'mode': 'cors',
'credentials': 'include',
}
})
.then(function(response) {
document.getElementById("rn0").textContent = response.data['m2m:cin'].rn;
var rn0 = response.data['m2m:cin'].rn;
document.getElementById("ty0").textContent = response.data['m2m:cin'].ty;
var ty0 = response.data['m2m:cin'].ty;
document.getElementById("ri0").textContent = response.data['m2m:cin'].ri;
document.getElementById("pi0").textContent = response.data['m2m:cin'].pi;
document.getElementById("ct0").textContent = response.data['m2m:cin'].ct;
document.getElementById("lt0").textContent = response.data['m2m:cin'].lt;
document.getElementById("st0").textContent = response.data['m2m:cin'].st;
document.getElementById("cnf0").textContent = response.data['m2m:cin'].cnf;
document.getElementById("cs0").textContent = response.data['m2m:cin'].cs;
document.getElementById("con0").textContent = response.data['m2m:cin'].con;
})
}
getDataLAMP_0();
InsertToDataBase.insertdatatolamp0(rn0,ty0);
this is the InsertToDataBase.js
const {Client} = require('pg')
const client = new Client({
user:"postgres",
password:"admin",
host:"localhost",
port:"5432",
database:"postgres",
})
function insertdatatolamp0(rn0,ty0){
client.connect()
.then(()=>console.log("connected successfuly"))
.then(()=>client.query("insert into lamp0 values ($1,$2)",[rn0,ty0]))
.catch(e=> console.log(e))
.finally(()=> client.end())
}
module.exports = { insertdatatolamp0 };
You can chain promises. This will give you enough flexibility to do a series of actions one after the other, in your case change textContent and then insert some values into the database.
const axios = require("axios");
const InsertToDataBase = require("./InsertToDataBase");
const username = "admin";
const password = "admin";
const token = Buffer.from(`${username}:${password}`, "utf8").toString("base64");
const urlLAMP_0 = "http://127.0.0.1:8282/~/mn-cse/mn-name/LAMP_0/DATA/la";
const urlLAMP_1 = "http://localhost:8282/~/mn-cse/mn-name/LAMP_1/DATA/la";
function getDataLAMP_0() {
axios
.get(urlLAMP_0, {
headers: {
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Origin": "*",
"X-M2M-RI": "OM2M-webpage",
Authorization: `Basic ${token}`,
Accept: "application/json",
mode: "cors",
credentials: "include",
},
})
.then(function (response) {
document.getElementById("rn0").textContent = response.data["m2m:cin"].rn;
document.getElementById("ty0").textContent = response.data["m2m:cin"].ty;
document.getElementById("ri0").textContent = response.data["m2m:cin"].ri;
document.getElementById("pi0").textContent = response.data["m2m:cin"].pi;
document.getElementById("ct0").textContent = response.data["m2m:cin"].ct;
document.getElementById("lt0").textContent = response.data["m2m:cin"].lt;
document.getElementById("st0").textContent = response.data["m2m:cin"].st;
document.getElementById("cnf0").textContent =
response.data["m2m:cin"].cnf;
document.getElementById("cs0").textContent = response.data["m2m:cin"].cs;
document.getElementById("con0").textContent =
response.data["m2m:cin"].con;
return response;
})
.then((response) => {
var rn0 = response.data["m2m:cin"].rn;
var ty0 = response.data["m2m:cin"].ty;
InsertToDataBase.insertdatatolamp0(rn0,ty0);
});
}
getDataLAMP_0();
You can do this with the help of Promise, here is a simple example
async function httpGetDataHandler() {
const url = "https://jsonplaceholder.typicode.com/posts";
const response = await fetch(url);
const parsedJson = await response.json();
const data = await parsedJson;
return Promise.resolve(data);
}
const getDataLAMP_0 = () => {
httpGetDataHandler()
.then((data) => {
// do your document.getElementById stuff in here
// I'm just returning the first index value, you can do whatever you want like return rn0
return data[0]
})
.then((data) => {
console.log("insert to database: ", data);
});
};
getDataLAMP_0();

NextJS: TypeError: Cannot read property 'json' of undefined

I've this code into pages folder on my NextJS environment. It gets data calling an external API Rest, and it's working because the console.log(response); line show me by console the Json API response. The problem I've is that I get this error in browser:
TypeError: Cannot read property 'json' of undefined
Corresponding with this line code:
const data = await res.json();
This is the complete file with the code:
import React from "react";
import fetch from "node-fetch";
const getFetch = async (invoicesUrl, params) => {
fetch(invoicesUrl, params)
.then((response) => {
return response.json();
})
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
};
export const getServerSideProps = async () => {
const invoicesUrl = "https://192.168.1.38/accounts/123456";
const params = {
method: "get",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
};
const res = await getFetch(invoicesUrl, params);
const data = await res.json();
console.log("Data Json: ", data);
return { props: { data } };
};
This is the Json API response that I see by console:
{
account: [
{
id: '7051321',
type: 'probe',
status: 'open',
newAccount: [Object],
lastDate: '2020-07-04',
taxExcluded: [Object],
totalRecover: [Object],
documentLinks: []
},
]
}
Any idea how can I solve it?
Thanks in advance.
UPDATE
Here the code working good:
import React from "react";
import fetch from "node-fetch";
const getFetch = async (invoicesUrl, params) => {
return fetch(invoicesUrl, params);
};
export const getServerSideProps = async () => {
const invoicesUrl = "https://192.168.1.38/accounts/123456";
const params = {
method: "get",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
};
try {
const res = await getFetch(invoicesUrl, params);
const data = await res.json();
console.log("Data JSON: ", data);
return { props: { data } };
} catch (error) {
console.log("Data ERROR: ", error);
}
};
There are a couple of things you have to change.
const getFetch = async (invoicesUrl, params) => {
fetch(invoicesUrl, params)
.then((response) => {
return response.json();
})
.then((response) => {
console.log(response);
return response; // 1. Add this line. You need to return the response.
})
.catch((err) => {
console.log(err);
});
};
export const getServerSideProps = async () => {
const invoicesUrl = "https://192.168.1.38/accounts/123456";
const params = {
method: "get",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
};
const data = await getFetch(invoicesUrl, params);
// const data = await res.json(); 2. Remove this you have already converted to JSON by calling .json in getFetch
console.log("Data Json: ", data); // Make sure this prints the data.
return { props: { data } };
};
You have return statement in wrong place.
When the function is expecting a return. You need to return when the statements are executed not inside the promise then function because it is an async callback function which is not sync with the statement inside getFetchfunction. I hope i have made things clear. Below is the code which will any how return something
import React from "react";
import fetch from "node-fetch";
const getFetch = async (invoicesUrl, params) => {
return fetch(invoicesUrl, params);
};
export const getServerSideProps = async () => {
const invoicesUrl = "https://192.168.1.38/accounts/123456";
const params = {
method: "get",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
};
try{
const res = await getFetch(invoicesUrl, params);
console.log("Data Json: ", res);
}catch(error){
console.log("Data Json: ", error);
}
return { props: { res } };
};

Vue - returning the result of a synchronous method

I'm struggling to return the synchronous results of the method below.
I call the method from a different method:
var result = this.getVendor(id)
console.log(result)
Here is the fetch method:
methods: {
async getData(id) {
const response = await fetch(`${API_URL}api/${id}`, {
method: "GET",
headers: {
authorization: `Bearer ${localStorage.token}`
}
})
.then(res => res.json())
.then(data => {
return data;
});
await response;
}
}
How do I return the results response of the getData() function to show in the console?
Async functions Always return a promise.
You can use the await syntax to return it properly.
async getData(id) {
const response = await fetch(`${API_URL}api/${id}`, {
method: "GET",
headers: {
authorization: `Bearer ${localStorage.token}`
}
})
const data = await response.json()
return data
}
You can access the data out of that function anywhere you call it.
let data = null
object.getData(2)
.then(x => {
data = x
})
Also if you are going to use async await make sure to use try and catch to handle any errors that come up.
async getData(id) {
try {
const response = await fetch(`${API_URL}api/${id}`, {
method: "GET",
headers: {
authorization: `Bearer ${localStorage.token}`
}
})
const data = await response.json()
return data
}
} catch(err) {
console.error(err)
}

Categories

Resources