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);
}
});
};
});
Related
Here is some code I've been working on:
let b = [];
for (let i = 0; i < res.length; i++) {
let fooFound = false;
const foo = require(`./modules/${res[i]}`);
rest.get(Routes.applicationCommands("BLAH")).then((c) => {
b = c;
if (b) {
b.forEach((command) => {
if (command.name === foo.name) {
fooFound = true;
}
});
if (fooFound === false) {
b.push({
name: foo.name,
description: foo.description,
});
}
}
});
}
console.log(b);
The problem that I am experiencing is that the code that is after the loop (here the console.log(b)) is running before the loop is finished.
I tried to get it to work with promises but couldn't solve it.
What you're facing is because the Promise completes later after the console.log(b); done.
Simplest approach to solve this just by wrapping it in async/await.
const myProgram = async () => {
let b = [];
const myLoop = async () => {
for (let i = 0; i < res.length; i++) {
let fooFound = false;
const foo = require(`./modules/${res[i]}`);
const c = await rest.get(Routes.applicationCommands("BLAH"));
b = c;
if (b) {
b.forEach((command) => {
if (command.name === foo.name) {
fooFound = true;
}
});
if (fooFound === false) {
b.push({
name: foo.name,
description: foo.description,
});
}
}
}
}
await myLoop();
console.log(b);
}
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
Sorry if this is extremely simple, I can't get my head around it. I've seen similar questions but nothing which gets to the heart of my problem, I think. I have a simple async function:
async function isOpen() {
var open;
var data = $.ajax({
//Working code here
});
data.done(function(dat) {
var obj = JSON.parse(dat);
var msg = "";
for (var i = 0; i < obj.length; i++) {
let closingDate = Date.parse(obj[i].close);
let openingDate = Date.parse(obj[i].open);
if (closingDate > Date.now() && openingDate < Date.now()) {
open = true;
} else {
open = false;
}
}
});
return open;
}
I know that this code is all working - using console.log I have seen that open is always successfully assigned to true or false. So I call this async function from another async function:
async function testFunction(){
const open1 = await isOpen();
//More code here...
}
But open1 (in testFunction) is always undefined - even though I use await.
Any ideas what this could be?
async function isOpen() {
var open;
var data = await $.ajax({
//Working code here
});
var obj = JSON.parse(data);
var msg = "";
for (var i = 0; i < obj.length; i++) {
let closingDate = Date.parse(obj[i].close);
let openingDate = Date.parse(obj[i].open);
if (closingDate > Date.now() && openingDate < Date.now()) {
open = true;
} else {
open = false;
}
}
return open;
}
of course, the value of open will be determined by the last obj[i]
So you want
async function isOpen() {
const data = await $.ajax({
//Working code here
});
const obj = JSON.parse(data);
let msg = "";
for (var i = 0; i < obj.length; i++) {
const closingDate = Date.parse(obj[i].close);
const openingDate = Date.parse(obj[i].open);
if (closingDate > Date.now() && openingDate < Date.now()) {
return true;
}
}
return false;
}
Or even
async function isOpen() {
const data = await $.ajax({
//Working code here
});
const obj = JSON.parse(data);
let msg = "";
return obj.some(({open, close}) => {
const closingDate = Date.parse(close);
const openingDate = Date.parse(open);
const now = Date.now();
return closingDate > now && openingDate < now();
});
}
This is happening because you are using a callback for ajax request and not waiting for ajax request to complete, which is going to set open in isOpen. You can return a Promise to resolve this,
function isOpen() {
return new Promise((resolve, reject) => {
var open;
var data = $.ajax({
//Working code here
});
data.done(function(dat) {
var obj = JSON.parse(dat);
var msg = "";
for (var i = 0; i < obj.length; i++) {
let closingDate = Date.parse(obj[i].close);
let openingDate = Date.parse(obj[i].open);
if (closingDate > Date.now() && openingDate < Date.now()) {
open = true;
} else {
open = false;
}
}
resolve(open);
});
}
}
Note: For the above code, you need to handle the logic for errors in the callback, using reject otherwise it will hang forever.
tldr at the bottom:
I don't really know how to explain my problem so I start with an example.
I have this async function (in reactJS but I think this is a JS related issue).
onUploadDrop = async (e, folderId) => {
e.preventDefault();
// check if the user uploaded files or folders
var uploadedItems = e.dataTransfer.items;
let files = [];
for (var i = 0; i < uploadedItems.length; i++) {
let item = uploadedItems[i].webkitGetAsEntry();
if (item.isDirectory) {
alert("is directory")
} else {
var file = await this.getFileByWebkitEntry(item);
files.push(file);
}
console.log(i);
}
// do something with files[]
}
This function is calling another async function:
getFileByWebkitEntry = async (item) => {
return new Promise(resolve => {
item.file(function (file) {
resolve(file);
}, function (err) {
console.log(err);
resolve("");
});
});
}
I'm looping through e.datatransfer.files which are basically some uploaded files or folders. Unfortunately this for-loop gets only executed once.
I did some debugging and found out that if I place a console.log before and after this line: var file = await ... This comes out:
tldr: After the await statement uploadedItems is empty thus ending the loop. Why is this happening?
I solved this by not using async - await but Promises instead.
It looks like this:
onUploadDrop = (e, folderId) => {
e.preventDefault();
// check if the user uploaded files or folders
var uploadedItems = e.dataTransfer.items;
let promises = [];
for (var i = 0; i < uploadedItems.length; i++) {
let item = uploadedItems[i].webkitGetAsEntry();
if (item.isDirectory) {
alert("is directory")
} else {
promises.push(this.getFileByWebkitEntry(item));
}
console.log(i);
}
Promise.all(promises).then(result => {
// do something with result (result = files)
});
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.