Export a variable from a function in Javascript - javascript

All i want is take userId variable's value to use anything.
async function getMyData(){
const token = '';
spotifyApi.setAccessToken(token);
const data = await spotifyApi.getMe();
let userId = data.body.id;
return userId;
}
const userId = getMyData();
console.log(userId)
console.log(userId) saying me this: {Promise <pending<}

With any async functions, don't forget to use await before function execution
/// ./getMyData.js
export async function getMyData(){
// ...
return userId;
}
/// ./otherFile.js
import {getMyData} from './getMyData.js'
(async function () {
const userId = await getMyData();
console.log(userId)
})()

you are using async await features in your code.
Thus the return type of your getMyData would actually be a Promise object.
More about Promises here
Now, heres how you can use your function in another file without having to use the await keyword.
import { getMyData } from '%your file path%';
getMyData().then(function(userId) {
// use the value of userId here
console.log(userId);
}

Related

Can I use variables that are inside functions outside them?

async function players_online() {
const response = await fetch("http://ip:port/dynamic.json");
const data = await response.json();
console.log(data.clients);
}
Can i use data inside other function? Exemple:
async function players() {
console.log(data.clients);
}
When i do this i recive undefined
"Yes", you can:
let data
async function players_online() {
const response = await fetch("http://ip:port/dynamic.json");
data = await response.json();
}
async function players() {
// You can't ensure data is already set!!!
console.log(data.clients);
}
However you can not ensure that data is already defined at that point. You have to ensure by your own code that players_online is called and awaited before you call players.
You can ensure this with a call order like that:
async function players_online() {
const response = await fetch("http://ip:port/dynamic.json");
const data = await response.json();
await players(data)
}
async function players(data) {
console.log(data.clients);
}

exporting multiple functions but always run default function first

Sorry for the bad description but I would like to create a "service.js" -file where I export multiple functions that retrieve data from a database.
something like:
...
import Person from '../models/Person'
import dbConnect from "../lib/dbConnect";
await dbConnect()
const save = async (person) => {
const savedPerson = await Person.save(person)
return savedPerson
}
const geAll = async () => {
const persons = await Person.find({})
return persons
}
...
export default { getAll, save };
But how do I always run dbConnect() when the exported functions are used in the code ? do I need to add the await dbConnect() to every function or is there some smarter way to do this ?
What about a class with await dbConnect() on constructor? Something like:
class MyClass {
constructor() {
return (async () => {
await dbConnect();
return this; // new instance created
})();
}
async save(person) {
const savedPerson = await Person.save(person)
return savedPerson
}
async geAll() {
const persons = await Person.find({})
return persons
}
}
Then:
const myClass = await new MyClass(); // <-- this calls dbConnect()
myClass.geAll();

No result is happening for this Web3.js call

const fs = require('fs')
const web3 = new Web3("ws://localhost:7545");
const contract_address = "0x7484d32e8911817702c5d7c764dBF7e592000b415";
async function web3Contract() {
const contract_abi = fs.readFileSync('./build/contracts/Bottle.json', 'utf8')
const abi = JSON.parse(contract_abi).abi;
// console.log(abi);
const Bottle = await new web3.eth.Contract(abi, contract_address);
const accounts = await web3.eth.getAccounts();
await Bottle.methods.setName("Palm").send({from:accounts[0]});
const greeting = await Bottle.methods.getGreeting().call();
console.log(greeting);
});
}
async function run() {
try {
await web3Contract();
} catch (err) {
console.log('Your error is this - ' , err);
} finally {
console.log('finally');
}
}
run();
getGreeting().call() is giving me this error. I tried numerous different ways and been stuck on here for hours. Not to sure what to do. https://gyazo.com/81970d03c1380cd513998f25deef9e40
You're incorrectly combining await and the callback function (in your case function(result) {}).
Since you're using await, it never reaches the callback function, and the returned Promise is resolved by the await statement.
In the context of your code, it makes more sense to return the value from the await and then print it.
// remove the callback function
const greeting = await Bottle.methods.getGreeting.call();
console.log(greeting);

NestJS TypeORMCrudService

I need to use one of the basic TypeORMCrudService methods, for example, createOne, I got the body as dto(I guess) but the second parameter is the CrudRequest. Should I redefine its methods or what?
if I understand what you mean:
if you use repositoryT it's so easy to do it:
your controller should be like this:
#Get(':id')
async findOne(#Param('id', ParseIdPipe) id: number) {
return await this.unitService.findOne(id);
}
your service should be like this:
async findOne(id: number, ...relations: string[]): Promise<Entity> {
const record = await this.repository.findOne(id, { relations });
this.checkNotFound(record);
return record;
}
you can use :
const record = await this.repository.findOne(id, { relations });
const record = await this.repository.create({dto});
const record = await this.repository.find();
const record = await this.repository.delete(id);
const record = await this.repository.update(id, {dto});

How to await on a promise that is returned in an array without destructuring first?

If I have something like,
const apiCall = async (url) => {
try {
const { data } = await axios.get(url);
return [url, data];
} catch ({ response: { data } }) {
console.log('Error', data);
}
}
Say I want to call and access the data from the promise. I'd have to do something like,
const [, call] = await validate('/api/root');
const data = await call;
Is there a way to do this in a one liner, without having to access the call, something like,
await (await validate('/api/root'))?
This is an equivalent one-liner:
const data = await (await validate('/api/root'))[1]
You can put an awaited function inside an argument. So something like
const result = await apiCall(
await validate(),
url
)
Then you could handle the validation inside apiCall.
Or you could just add the validate function as a callback inside apiCall if it's dependent on the result of apiCall.

Categories