Await is not as i expected in if else statements [duplicate] - javascript

This question already has answers here:
Using async/await with a forEach loop
(33 answers)
Closed 10 months ago.
let metadata = [];
allNFTs.map(async (e) => {
if (e.metadata) {
metadata.push(JSON.parse(e.metadata).attributes);
} else {
let config = {
method: "get",
url: `http://localhost:3000/api/fetch`,
header: {
"Content-Type": "application/json",
},
};
const res = await axios(config);
const attr = res.data.attributes;
metadata.push(attr);
console.log(metadata); // this one worked after below
}
});
console.log(metadata); // this one worked before above
But i want to wait till my axios done fetching, so i can finally console.log that my actual metadata.

Make an array of promises, and then await them with Promise.all
const metadataPromises = allNFTs.map((e) => {
if (e.metadata) {
return Promise.resolve(JSON.parse(e.metadata).attributes);
} else {
let config = {
method: "get",
url: `http://localhost:3000/api/fetch`,
header: {
"Content-Type": "application/json",
},
};
return axios(config).then((res) => res.data.attributes);
}
});
// await still has to be in an async function
const metadata = await Promise.all(metadataPromises);
console.log(metadata);
// or use .then
Promise.all(metadataPromises).then((metadata) => console.log(metadata));

The issue with you code, that you don't wait. The latest console.log is execurted before the map iterating all the items.
You should use somehting like that: https://www.npmjs.com/package/modern-async
E.g.
async function init() {
var ma= require('modern-async')
await ma.mapSeries(allNFTs,async (e)=>{
if (e.metadata) {
metadata.push(JSON.parse(e.metadata).attributes);
} else {
let config = {
method: "get",
url: `http://localhost:3000/api/fetch`,
header: {
"Content-Type": "application/json",
},
};
const res = await axios(config);
const attr = res.data.attributes;
metadata.push(attr);
console.log(metadata);
}
})
console.log(metadata);
}

Related

await function returns Undefined [duplicate]

This question already has answers here:
Waiting for the fetch to complete and then execute the next instruction
(2 answers)
How can I return the fetch API results from a function?
(5 answers)
Closed last month.
My goal is to "pause" the EventListener function in order to get something done by calling another function (getCategoriesIDs) that returns a value that I will use to continue the EventListener function execution.
When I log the categoriesIDtoNameMapped after the execution it comes out as UNDEFINED.
Would greatly appreciate your help.
form.addEventListener("submit", async (e) => {
//do something
try {
let categoriesIDtoNameMapped = await getCategoriesIDs()
console.log(categoriesIDtoNameMapped)
} catch (err) {
console.log(err)
}
//do something with the categoriesIDtoNameMapped
}
function getCategoriesIDs() {
fetch('http://localhost:1337/api/categories', {
method: 'GET',
headers: {
'Content-type': 'application/json',
Authorization: `Bearer ${JWT_TOKEN}`
}
})
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then((response) => {
const categoriesIDtoNameMapped = {}
for (let i = 0; i < response.data.length; i++) {
categoriesIDtoNameMapped[response.data[i].id] = response.data[i].attributes.name
}
return new Promise(resolve => {
resolve(categoriesIDtoNameMapped)
});
});
}
Your getCategoriesIDs needs to be an async function for you to await something on it.
To fix this you need make getCategoriesIDs as async function and use await for fetch
async function getCategoriesIDs() {
const response = await fetch('http://localhost:1337/api/categories', {
method: 'GET',
headers: {
'Content-type': 'application/json',
Authorization: `Bearer ${JWT_TOKEN}`
}
})
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const responseJson = await response.json();
const categoriesIDtoNameMapped = {}
for (let i = 0; i < response.data.length; i++) {
categoriesIDtoNameMapped[responseJson.data[i].id] = response.data[i].attributes.name
}
return categoriesIDtoNameMapped;
}

How to return the fetch from an async call [duplicate]

This question already has answers here:
async/await always returns promise
(4 answers)
Closed 2 months ago.
I'm really confused about asynchronous functions in general, but I can't seem to return what the api has fetched. Using console.log() gives all the results but I need the function's path (array) for later use.
function callRelation(id) {
(async () => {
const api = await fetch(
"https://www.overpass-api.de/api/interpreter?",
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: "[out:json];rel(" + id + ");(._;>;);out;",
},
);
const request = await api.json();
let path = [];
for (let pair of request.elements){
if (pair.type === "node"){
path.push([pair.lat, pair.lon]);
}
}
console.log(path)
return path;
})();
}
let test = callRelation(10000);
console.log(test);
I've tried using something called a callback, but I failed miserably at that.
You await to get return from promise function.
async function callRelation(id) {
const api = await fetch("https://www.overpass-api.de/api/interpreter?", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: "[out:json];rel(" + id + ");(._;>;);out;",
});
const request = await api.json();
let path = [];
for (let pair of request.elements) {
if (pair.type === "node") {
path.push([pair.lat, pair.lon]);
}
}
console.log(path);
return path;
}
(async function () {
let test = await callRelation(10000);
console.log(test);
})();

How do I return an item from an async funtion

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;

Wait for return value from function with async call in javascript [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 1 year ago.
I have a set of if-else conditions which calls a few functions and attribute properties to usr before redirecting this data to an external application.
if(funcA()) {
usr.a = funcA();
}
if(funcB()) {
funcB(user,context,function (error, ticket) {
usr.ticket = ticket;
});
}
redirect(usr);
funcB has two async API calls (using axios) and the script always trickles down to redirect before funcB returns a value.
function funcB(user, context, callback) {
let ticket = '';
const axios = require('axios#0.19.2');
const options = {method: 'POST', url: 'xxxx', data: '{xxxx}'};
axios(options).then(res => {
const access_token = res.data.access_token;
const options = {method: 'POST', url: 'xxx', data: `{xxxx}` };
axios(options).then(res => {
ticket = res.data.ticket;
callback(null, ticket);
}).catch(err);
}).catch(err);
}
I have tried using callback and async await but unsure how to wait for user.Ticket to be populated before redirect(usr) is called.
Making funcB return a promise should do the trick.
function funcB(user, context) {
return new Promise((resolve, reject) => {
const options = { method: "POST", url: "xxxx", data: "{xxxx}" };
axios(options)
.then((res) => {
const access_token = res.data.access_token;
const options = { method: "POST", url: "xxx", data: `{xxxx}` };
axios(options)
.then((res) => {
resolve(res.data.ticket);
})
.catch(reject);
})
.catch(reject);
});
}
Then use async await
if(funcB()) {
usr.ticket = await funcB(user,contex)
}
redirect(usr);
Edit: im assuming that the context where the if condition is running is already an async function if not you can do this
(async ()=>{
if(funcB()) {
usr.ticket = await funcB(user,contex)
}
redirect(usr);
})()

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