angularjs combine two Trello api and assign it to $rootScope variable - javascript

Hello there I have a function that will combine two API from Trello.
if I console.log, it will give the result correctly:
but I Would like to assign it's value to a $rootScope so I can use it to the component.
my .run() code:
angular.module('workTrello', [
'ngRoute'
])
.config()
.run(function($rootScope){
async function trelloCards() {
let response = await fetch(`https://api.trello.com//1/boards/5ba38efef50b8979566922d0/cards?key=${key}&token=${token}`);
return await response.json();
}
async function trelloLists() {
let response = await fetch(`https://api.trello.com/1/boards/5ba38efef50b8979566922d0/lists?key=${key}&token=${token}`)
return await response.json();
}
async function bindWorkInfo() {
const cards = await trelloCards();
const lists = await trelloLists();
let trelloWorkData = [];
for (let i = 0; i < lists.length; i++) {
const list = lists[i];
list.name = list.name.substr(0,list.name.indexOf(' '))
let listWithCard = [];
for (let x = 0; x < cards.length; x++) {
const card = cards[x];
if (card.idList == list.id) {
try { /** 8-12+14-16 = 6*/
card.name = Math.abs(eval(card.name));
listWithCard.push({
id:list.id, date:list.name, idCard:card.id,
time:card.name, task:card.badges.checkItemsChecked,
idMember:card.idMembers[0]
});
} catch (error) {}
}
}
trelloWorkData.push(listWithCard);
}
console.log(trelloWorkData)
return trelloWorkData;
}
bindWorkInfo().then((res) => $rootScope.workedInfo = res);
}
this my attempt :
bindWorkInfo().then((res) => $rootScope.workedInfo = res);
but when I access $rootScope.workedInfo from the component it will return as undefined.
anyone know the correct way of assigning it to $rootScope ?

you have to return a promise to make the function thennable. change the following return code
return trelloWorkData;
to
return Promise.resolve(trelloWorkData);
and try.

Related

How to wait an item to be saved in Parse Library in Javascript?

I am ordering some items with their priorities. I used a loop for that. However, I get some weird outputs like [1,1,2,2,3] instead of [1,2,3,4,5](these are priorities btw). The loop is below.
const switchPriority = async function(catId, srcI, destI){
let indexofCat;
try {
for (let i = 0; i < data[0].length; i++) {
const element = data[0][i];
if(element.id === catId){
indexofCat = i;
}
}
let Item = Parse.Object.extend('Item')
let itemQuery = new Parse.Query(Item)
for (let i = (srcI>destI?destI:srcI); i < (srcI>destI?(srcI+1):(destI+1)); i++) {
let id = data[1][indexofCat][i].id;
let item = await itemQuery.get(id);
item.set("priority",i+1);
await item.save();
}
} catch (error) {
alert(error)
}
}
Why there is such a problem? When I add alert to the loop, with some delay it gives proper outputs. How can I solve this ? I am appreciate for your help.
I don't know if you forgot, but it's necessary use the word async like this await works. You can insert your code into a function:
async function parse(){
for (let i = (srcI); i < (destI); i++) {
// alert("index in loop "+ i);
let id = data[1][indexofCat][i].id;
let item = await itemQuery.get(id);
// alert(item.get("name"));
item.set("priority",i+1);
await item.save();
}
}
Look at for more details: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Statements/async_function
You can also promisify a function that you needs to guarantee that it be executed before the next instruction. How?
function createPromise (parameter) {
return new Promise((resolve, reject) => {
resolve(console.log(parameter))
})
}
async function test(){
console.log('First')
await createPromise('Promise')
console.log('Second')
}
test()
Look at: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Promise

PromiseĀ {<pending>} being returned and await key word not working [duplicate]

This question already has an answer here:
Getting Promise pending ..- ES6
(1 answer)
Closed 12 months ago.
When running the below code and dumping out the results variable it returns PromiseĀ {<pending>}, I have added the await key word to the being of the function call so const results = await getAllResults() however this returns the error of Unexpected reserved word 'await'.
Anyone have any ideas?
useEffect(() => {
async function getPageOfResults(page) {
const response = await axios.get('https://swapi.dev/api/starships/?page=' + page);
return response.data.results;
}
async function getAllResults() {
let starships = [];
let lastResultsLength = 10;
let page = 1;
while (lastResultsLength === 10) {
const newResults = await getPageOfResults(page);
page++;
lastResultsLength = newResults.length;
starships = starships.concat(newResults);
}
return starships;
}
const results = getAllResults();
}, []);
You need to add async in the useEffect like so:
useEffect(async () => {
async function getPageOfResults(page) {
const response = await axios.get('https://swapi.dev/api/starships/?page=' + page);
return response.data.results;
}
async function getAllResults() {
let starships = [];
let lastResultsLength = 10;
let page = 1;
while (lastResultsLength === 10) {
const newResults = await getPageOfResults(page);
page++;
lastResultsLength = newResults.length;
starships = starships.concat(newResults);
}
return starships;
}
const results = await getAllResults();
}, []);

Node.js How to retrieve data from http.get response

I am doing some practice in node.js. In this exercise I been asked to find a country name through a GET Http Request to an endpoint passing a page integer as a parameter.
Where the important response structs are these {page, total_pages, data}.
page is the current page,
total_pages is the last page,
data is an array of 10 country object.
In getCountryName func I am able to retrieve the right answer only if the answer is on the 1st page, the 1 iteration of the loop. So, why the loop only happens once?
Aditional, I wanted to retrieve the total_pages to replace the hardcode '25' value but I do not figure it out how to return it along with the search.
Any hint you wanna give me? The whole problem is in getCountryCode func.
'use strict';
const { Console } = require('console');
const https = require('https');
function makeRequest(page){
return new Promise(resolve => {
let obj='';
https.get('https://jsonmock.hackerrank.com/api/countries?page='+page, res => {
let data ='';
res.on('data',function(chunk){
data+=chunk;
});
res.on('end',function(){
obj=JSON.parse(data);
resolve(obj);
});
});
});
}
async function getCountryName(code) {
var res = '';
var pages = 25;
var i = 1;
while(i <= pages && res == ''){
console.log(i);
res = makeRequest(i)
.then(data => {
let f = ''
let p = data['total_pages'];
let search = data['data'].find(o => o.alpha3Code === code);
f = search != null ? search['name'] : f;
return f;
});
i++;
}
return res;
}
async function main() {
const name = await getCountryName('ARG');
console.log(`${name}\n`);
}
main();
Without modifying your code too much, this is how you do it:
'use strict';
const { Console } = require('console');
const https = require('https');
function makeRequest(page){
return new Promise(resolve => {
let obj='';
https.get('https://jsonmock.hackerrank.com/api/countries?page='+page, res => {
let data ='';
res.on('data',function(chunk){
data+=chunk;
});
res.on('end',function(){
obj=JSON.parse(data);
resolve(obj);
});
});
});
}
async function getCountryName(code) {
const pages = 25;
var i = 1;
let f = null
while(i <= pages && f === null){
console.log(i);
const data = await makeRequest(i) // put in try/catch
const p = data['total_pages'];
const search = data['data'].find(o => o.alpha3Code === code);
f = search !== null ? search['name'] : null;
i++;
}
return res;
}
async function main() {
const name = await getCountryName('ARG');
console.log(`${name}\n`);
}
main();

Mongoose Query FindOne with array

So i want to verify if a value is inside the collection. I've managed to do it using .map. My code looks like this (the field is nested):
const loopFields = [
"nested.field1",
"nested.field2",
"nested.field3",
"nested.field4"
];
async function getField() {
const field = loopFields.map(async (fld, idx) => {
const result = await Field.findOne({ [fld]: req.body.field });
if (result) {
return fld;
}
});
const isFound = await Promise.all(field);
for (i = 0; i < loopFields.length; i++) {
if (isFound[i] !== undefined) {
return true;
}
}
}
const isValid = await getField();
if (!isValid) {
return res.status(400).send("Field not found");
}
The code does work but i'm looking for a way to reffactore it.
build an $or clause dynamically and pass it to the find method like so:
var loopFields = [
"nested.field1",
"nested.field2",
"nested.field3",
"nested.field4"
];
var fields = loopFields.map(field => {
var x = {};
x[field] = req.body.field;
return x;
})
db.collection.find({ $or: fields });

Express app.use does not send correct fake data

I was practicing Express 4.x and noticed the following:
app.get('/fake', function(req, res) {
var obj = [];
for (let i = 0; i < 3; i++) {
jsf.resolve(fakeSchema).then(function(iter) {
obj.push(iter);
});
}
res.send(obj);
});
So, going to that route, I get "[ ]", while I was expecting to receive an array of 3 (fake) documents.
FYI, when logging each loop, I can clearly see the documents generated, even inside the array.
Any explanation?
Your jsf.resolve functiion is async so you can use async/await for this to perform task in sync manner.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
app.get('/fake', async function(req, res) {
var obj = [];
for (let i = 0; i < 3; i++) {
try {
var iter = await jsf.resolve(fakeSchema);
obj.push(iter);
} catch (e) {}
}
res.send(obj);
});
Although #Nishant's provided answer works, I suggest using this approach.
let jsf = {};
// faking your jsf.resolve method
jsf.resolve = (param) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Math.random());
}, 1000);
})
};
let fakeSchema = {};
let obj = [];
let promises = [];
for (let i = 0; i !== 3; i++) {
promises.push(jsf.resolve(fakeSchema).then(function (iter) {
obj.push(iter);
}));
}
Promise.all(promises).then(() => {
console.log(obj);
});
This allows all the promises to run concurrently, imagine your jsx.resolve takes a long time to complete, using await would freeze your entire appp.
As opposed to this. Note the runtime.
(async () => {
let jsf = {};
// faking your jsf.resolve method
jsf.resolve = (param) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Math.random());
}, 1000);
})
};
let fakeSchema = {};
let obj = [];
for (let i = 0; i !== 3; i++) {
obj.push(await jsf.resolve(fakeSchema));
}
console.log(obj);
})();
#Nishant Dixit's answer also correct!
You can try this simple solution also, if you like :
app.get('/fake', function(req, res) {
var obj = [];
for (let i = 0; i < 3; i++) {
try {
jsf.resolve(fakeSchema).then(function(iter) {
obj.push(iter);
res.send(obj);
} catch (e) {
res.send(e);
}
});
};
});

Categories