How can I convert this promise back into JSON array - javascript

I code this to get a JSON array from my sever
var students_list;
const library_address = 'http://localhost:17330'
async function data(a,b) {
if(a == 'getdata')
{
const respone = await fetch(library_address + `/${a}/${b}`);
const output = await respone.json();
console.log(output);
return output;
}
}
But the problem is I can't get the array outside of that function, the result give me a promise object instead
students_list = data('getdata','student') //promise

var students_list;
const library_address = 'http://localhost:17330'
async function data(a,b) {
if(a == 'getdata')
{
const respone = await fetch(library_address + `/${a}/${b}`);
const output = respone.json(); // just delete await
console.log(output);
return output;
}
}
Once you use async, response will be a Promise object. You need use await to get what you want.

Related

How to wait till I get the secret values from Keyvault in Node JS?

I am fairly new to Javascript and I understand that it executes asynchronously. I tried using the callback method to fetch the secret values and then execute next block of code. But it is not waiting.
This is the function that fetches the keyvault secret values
function getsecret_values(client,secret_name,callback) {
let val = []
for (let i =0;i<secret_name.length;i++){
client.getSecret(secret_name[i]).then((latestSecret) => {
val[i] = latestSecret.value;
})
}
callback(val)
}
I am calling getsecret_values function from main block
let vaultName = result.database;
const url = `https://${vaultName}.vault.azure.net`;
const credential = new ClientSecretCredential(result.host, result.user, result.password);
const client = new SecretClient(url, credential);
let secret_values = []
getsecret_values(client, secrets, function(result) {
secret_values = result
console.log(secret_values)
});
console.log(secret_values)
\\next code block
Both the console.log returns empty array.
I want my code to wait till the secret values are fetched and put into secret_values array and then proceed to next block of code. How do I achieve this?
the easiest way is to use Async Await pattern, which uses promises in the background. Trying not to change your code much:
async function getsecret_values(client,secret_name) {
let val = []
for (let i =0;i<secret_name.length;i++){
const latestSecret = await client.getSecret(secret_name[i])
val[i] = latestSecret.value;
}
return val
}
in your main block:
getsecret_values(client, secrets).then(function(result) {
secret_values = result
console.log(secret_values)
});
console.log(secret_values) // will still be an empty array as the then function has not been executed yet....
my approach would be:
async function getsecret_values(client,secret_name) {
let val = []
for (let i =0;i<secret_name.length;i++){
const latestSecret = await client.getSecret(secret_name[i])
val[i] = latestSecret.value;
}
return val
}
// main:
async function main() {
let vaultName = result.database;
const url = `https://${vaultName}.vault.azure.net`;
const credential = new ClientSecretCredential(result.host, result.user, result.password);
const client = new SecretClient(url, credential);
const secret_values = await getsecret_values(client, secrets)
console.log(secret_values)
}
main()

Promise returns undefined nodejs

i am back with a same issue for my promise returning undefined please help.
Here, i am using ipfs to save data with savedata() which takes in a json string,a document name and a secret phrase.
i am not quit sure why promise is returning undefined i have checked everything
here is the new code
index.js
exports.savedata = async function savedata(jsondata,Docname,secretuuid){
const docname = Docname
let ipfss = await main();
let datavar = await ipfss.add(jsondata);
//check if input file exists or not?
const fpath = __dirname + "\\"+ "input.json"
if (fs.existsSync(fpath)) {
}
else{
const defobj = {defaultID:"defaultID"}
fs.writeFile("input.json",JSON.stringify(defobj),function(err){
// console.log('saved!')
})
}
//create an object and put an array with defaultid:defaultid to it
//take that object and keep concatenating the new arrays[new documents]
fs.readFile("input.json","utf-8",function(err,data){
if(err){
console.log(err)
}
const rembrk1 = data.replaceAll("{","")
const rembrk2 = rembrk1.replaceAll("}","")
const newstring = JSON.stringify({[docname]: datavar.path})
const URK = uuidv4() + "rkbyavds"
const CAT = CryptoJS.AES.encrypt(String(datavar.path),secretuuid);
var ENCAT = CAT.toString()
const fstring = "{" + rembrk2 + "," + docname + ":" + CAT + "}"
fs.writeFile("input.json", JSON.stringify(fstring),function(err){
if(err){
console.log(err)
}
})
return new Promise((resolve,reject) => {
// console.log('saved')
const retobj = {CAT:ENCAT,URK:URK}
resolve(retobj)
});
})
}
test.js
obj = JSON.stringify({user:"MqwMedz2edemusaaa",age:1291})
const op = savedata(obj,"doc1","verysecretuuid")
op.then(x=>{
console.log(x)
})
Well, the RegisterUser function executes the actions and retrieves the data. What it doesn't do is return any value. This means it'll return a Promise by default, but this Promise won't have any value to resolve.
Depending on which object you want to have returned, you need to return it or create and return a new Promise from which you can call the resolve-function.
You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

How to compare the value resulting from two promises in Javascript?

async function getDNShomeIP(){
var response = await fetch('https://dns.google/resolve?name=example.com'); // this uses the google api
var json = await response.json();
var homeIPadress = json.Answer[0].data;
console.log(homeIPadress);
return homeIPadress;
};
async function getCurrentIP(){
var response = await fetch("https://api.ipify.org?format=json");
var json = await response.json()
var currentIPadress = json.ip;
return currentIPadress;
}
var homeIPadress = getDNShomeIP();
var currentIPadress = getCurrentIP();
if (homeIPadress == currentIPadress){
alert("from same from lol");
} else {
alert("not from same")
};
Hi there,
I wanted to know how to compare the values of two promises in Javascript.
I can't work out how to make the program wait before the if statement.
The statement just evaluates to false if the promises are not yet fulfilled so program follows the else branch.
Thanks
Use the "await" keyword inside another "async" function so that the function waits for a response before it continues execution.
async function testEquality() {
var homeIPadress = await getDNShomeIP();
var currentIPadress = await getCurrentIP();
if (homeIPadress === currentIPadress) {
alert("from same from lol");
} else {
alert("not from same")
};
}
testEquality();
I would also recommend you use triple equal (===) to compare the results as this uses strict equality comparison.
You could wrap it in another async function:
async function execute() {
var homeIPadress = await getDNShomeIP();
var currentIPadress = await getCurrentIP();
if (homeIPadress == currentIPadress){
alert("from same from lol");
} else {
alert("not from same");
}
}
execute();
first you need to fix your fetch function, then fix the async await function
you have to put your await function on async function just like this,
fix your getdnshomeip just like the code below
function getCurrentIP(){
return fetch("https://api.ipify.org?format=json")
.then( r => r.json())
.then( r => r);
}
const check = async () => {
var currentIPadress = await getCurrentIP();
var homeIPadress = await getDNShomeIP();
if (homeIPadress === currentIPadress){
alert("from same from lol");
} else {
alert("not from same")
};
}
check();
You're describing a function I created
async function getDNShomeIP(){
var response = await fetch('https://dns.google/resolve?name=example.com');
var json = await response.json();
var homeIPadress = json.Answer[0].data;
console.log(homeIPadress);
return homeIPadress;
};
async function getCurrentIP(){
var response = await fetch("https://api.ipify.org?format=json");
var json = await response.json()
var currentIPadress = json.ip;
console.log(currentIPadress);
return currentIPadress;
}
const { eq } = rubico
eq(getDNShomeIP, getCurrentIP)().then(console.log)
<script src="https://unpkg.com/rubico/index.js"></script>
documentation for eq

Can an async function return undefined instead of a Promise [duplicate]

This question already has answers here:
Removing undefined values from Array
(14 answers)
Closed 3 years ago.
I am working on an app using nodejs. I am making multiple HTTP requests with an async function and axios library. However I do not always want to return the fetched data from my http request, only if a certain condition is met.
Like so.
const getFooHTTP = async (id) => {
let response = await axios.get(url);
if (condition){
//I only want to return the response here
return response;
}
//Here i do not want to return the response
}
Then I am getting all the promises returned in an array with Promise.all()
const getAllData = async() => {
let dataArray = [];
for (let i = 0; i < n; i++){
const data = getFooHTTP(i);
dataArray.push(data)
}
const someData = await Promise.all(dataArray);
return someData ;
}
Then I get all the data
getAllData().then(data => {
//Here is the problem, here I get a bunch of undefined in my data array
console.log(data);
})
Here is my problem, when I get the returned data from getAllData, there is some undefined element because at the first function in the beginning (getFooHTTP) was returning nothing. My question is how can I return promises conditionally, so I don't get undefined promises returned even If the async function have no return statement.
Thank you
An async function will always return a Promise, no matter what. If you explicitly return a non-Promise even if there are no awaits before it, it will be automatically wrapped in a Promise before returning (eg return undefined will turn into something like return Promise.resolve(undefined)).
const prom = (async () => {
return undefined;
})();
// Even though it returned undefined, it's still a Promise:
console.log(typeof prom.then);
If you don't want to return values that don't fulfill condition, filter the Promise.all before returning it:
const getFooHTTP = async (id) => {
let response = await axios.get(url);
if (condition){
//I only want to return the response here
return response;
}
//Here i do not want to return the response
return undefined;
// or, have no return statement at all
};
and
const getAllData = async() => {
let dataArray = [];
for (let i = 0; i < n; i++){
const data = getFooHTTP(i);
dataArray.push(data)
}
const someData = (await Promise.all(dataArray))
.filter(val => val !== undefined);
return someData ;
};
Though, this relies on all of the Promises that getFooHTTP resolves to returning non-undefined values.

How can I access and use a return value from a do while loop?

I am trying to access return data from a do while loop, but I am unable to do so.
I have stored the information in a new variable (starships) and then returned this variable, but it says starships is not defined. I see that this may be a scoping issue, how can I resolve this?
async function getData() {
const allResults = [];
let url = 'https://swapi.co/api/starships/';
do {
const res = await fetch(url);
const data = await res.json();
url = data.next;
allResults.push(...data.results);
console.log(allResults);
} while (url !== null)
let starships = allResults;
return starships;
}
console.log(starships);
You need to get the value which is returned from getData. The most obvious way to do this with the async/await structure you have is to just await it:
async function getData() {
const allResults = [];
let url = 'https://swapi.co/api/starships/';
do {
const res = await fetch(url);
const data = await res.json();
url = data.next;
allResults.push(...data.results);
console.log(allResults);
} while (url !== null)
let starships = allResults;
return starships;
}
async function doTheDo() {
const test = await getData();
console.dir(test);
}
doTheDo();
you can do this. starships is defined inside the loop. Additionally, you are not calling getData() function. You can store that return value like this
const result = await getData();
console.log(result);
or you can directly print like this. console.log(await getData())
async function getData() {
const allResults = [];
let url = 'https://swapi.co/api/starships/';
do {
const res = await fetch(url);
const data = await res.json();
url = data.next;
allResults.push(...data.results);
console.log(allResults);
} while (url !== null)
return allResults;
}
console.log(await getData());
Async functions return a promise, which means you have to access the return value with a .then().
However, you have another problem: starships is in the scope of the function getData() which you have defined, but not called.
So first lets call your function:
async function getData() {
const allResults = [];
// do stuff
let starships = allResults;
return starships;
}
console.log(getData());
Now you will see that your log value is [object Promise] which isn't so helpful in its current form. This is because the code outside the async function is running synchronously, which means we don't have the value yet, just a promise to maybe return the value sometime in the future.
So now we need to access the promise asynchronously using the .then() like so:
async function getData() {
const allResults = [];
// do stuff
let starships = allResults;
return starships;
}
getData().then(starships => {
console.log(starships);
});
Now you should see the info you were expecting to be logged.
You can also save promise to a variable and pass it around and access it elsewhere in your code like so:
async function getData() {
const allResults = [];
// do stuff
let starships = allResults;
return starships;
}
let starshipPromise = getData();
// time & code passes...
starshipPromise.then(starship => {
console.log(starship);
}).catch(error => {
// handle error
});
And don't forget to catch your rejected promises!
See the MDN docs on Async functions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
And if you need more info on promises, go here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Categories

Resources