Can't pass variable outside the scope of a Sequalize promise [duplicate] - javascript

This question already has answers here:
How to return value from an asynchronous callback function? [duplicate]
(3 answers)
Closed 7 years ago.
Here is a bit of code to demonstrate my issue.
'use strict';
module.exports = function(sequelize, DataTypes) {
var Game = sequelize.define('Game', { ... }, {
tableName: 'games',
instanceMethods: {
getState: function(userClass) {
var currentGame = this;
var gameState = {};
userClass.findOne({ where: { id: currentGame.challenger_user_id }}).then(
function(challengerUser) {
userClass.findOne({ where: { id: currentGame.recipient_user_id }}).then(
function(recipientUser) {
var turn;
if (currentGame.turn_symbol == 'X') {
turn = { user: challengerUser, symbol: 'X' };
} else {
turn = { user: recipientUser, symbol: 'O' };
}
gameState.game = currentGame;
gameState.turn = turn;
gameState.participants = [
{ user: challengerUser, symbol: 'X' },
{ user: recipientUser, symbol: 'O' }
];
console.log(gameState);
// Shows the object with the assigned values
}
);
}
);
console.log(gameState)
// Shows an empty object.
}
},
classMethods: { ... }
});
return Game;
};
In the getState function, we first declare an empty object named gameState.
We then find two users -- so we're now nested within two scopes -- and try to assign a value to our gameState variable.
When doing a console.log within the two nested scopes, the object is shown with all of the assigned values.
gameState is shown to be an empty object when doing a console.log outside of the two nested scopes (after assigning values).
Can someone help explain my error here?
Also, what is the correct term for these nested scopes -- are they promises?
Thanks!

Okay, I thought of a possible solution immediately after writing the question.
The reason why the console.log(gameState) at the end of the getState function returns null is because it runs asynchronous to the sequelize promises.
In other words, the server took .05 milliseconds to get to the last console.log(gameState), but the server took .15 milliseconds to get to where values are assigned to it.
^ Is that correct?

Related

assign variable to value of Dictionary Javascript

I am building a dictionary but I would like some of the values to contain variables. is there a way to pass a variable to the dictionary so I can assign a dot notation variable? the variables object will always have the same structure and the dictionary will be static and structured the same for each key value pair. essentially I want to pass the value from the dictionary to another function to handle the data.
main.js
import myDictionary from "myDictionary.js"
const variables ={
item:"Hello"
}
const data = myDictionary[key](variables)
console.log(data)
myDictionary.js
const myDictionary = {
key: variables.item
}
so the log should display hello. I know it willl be something straightforward but cant seem to figure it out.
as always any help is greatly appreciated
You should modify the dictionary so that it keeps actual callback functions instead. Only then it will be able to accept arguments.
const myDictionary = {
key: (variables) => variables.item
}
const variables = {
item: "Hello"
}
const key = "key";
const data = myDictionary[key](variables)
console.log(data)
What you are trying to do is not possible. The myDictionary.js file has no idea whats inside you main file. The only thing you could do would be:
myDictionary.js
const myDictionary = {
key: "item"
}
main.js
import myDictionary from "myDictionary.js";
const variables = {
item: "Hello"
};
const data = variables[myDictionary["key"]];
console.log(data);
Also, even though JavaScript does not enforce semi-colons, they will save you a lot of headaches of some stupid rule that breaks the automatic inserter.
I must apologise as when I asked the question I wasn't fully clear on what I needed but after some experimentation and looking at my edge cases and after looking at Krzysztof's answer I had a thought and came up with something similar to this -
const dict = {
key: (eventData) => {
return [
{
module: 'company',
entity: 'placement',
variables: {
placement_id: {
value: eventData.id,
},
},
},
{
module: 'company',
entity: 'placement',
variables: {
client_id: {
value: eventData.client.id,
},
},
},
];
},
}
Then I'm getting the data like this -
const data = dict?.[key](eventData)
console.log(data)
I can then navigate or manipulate the data however I need.
thank you everyone who spent time to help me

Why is the class creating an object with possibilities property undefined?

I'm trying to check an object (customer) against another object (developers), there are multiple developers so I have an object which houses all of them and I'm iterating through object that holds the developer, when a customer tests positive for the age condition then a test string is pushed onto the gateKeeper. possibilities property and in turn creates a new customer object from the customer class however, when I run gatekeeper.build(prospect, developers) pass it to a variable and console.log that variable it shows the possibilities properly as undefined, but when I console.log from inside the promise it shows it passed, for both developers, meaning it is pushing 'worked' onto the possibilities property but it isn't using that value when It builds the class, why?
edit
This now does as expected, I replaced the promise chain with a callback chain however as I understand it; the promise syntax paired with async await is the most correct way to execute functions when the timing of execution is important. I think I might be missing something as it regards to promises because code running within the promise chain executes but doesn't seem to affect anything outside the promise chain. If this is the case then (in my limited experience lol) I can't see any use case for the promises or the async await syntax, can someone please help me clarify this?
age: 28,
income: 75,
maritalStatus: 'Married',
majorCc: 'Y',
zipCode: 32805,
possibilities: {}
};
var developers = {
westgate: {
name: 'Westgate',
aTop: 68,
aBot: 28,
income: 50,
majorCc: 'Not Required',
maritalStatus: ['Married', 'Co Hab'],
payload: ['Myrtle Beach', 'Orlando', 'Gatlinburg', 'Cocoa Beach']
},
bluegreen: {
name: 'Bluegreen',
aTop: 999,
aBot: 25,
income: 50,
majorCc: 'Not Required',
maritalStatus: ['Married', 'Single Male', 'Co Hab', 'Single Female'],
payload: ['Myrtle Beach', 'Orlando', 'Gatlinburg', 'Cocoa Beach']
},
};
let gateKeeper = {
prospect: {},
settings: {},
possibilities: [],
methods: {
age(callback1) {
if (gateKeeper.prospect.age >= gateKeeper.settings.aBot && gateKeeper.prospect.age <= gateKeeper.settings.aTop) {
callback1();
}
},
income(callback) {
if (gateKeeper.prospect.income >= gateKeeper.settings.income) {
callback();
}
},
createPayload() {
var cache = {};
cache[gateKeeper.settings.name] = gateKeeper.settings.payload;
gateKeeper.possibilities.push(cache);
},
packageMethods() {
gateKeeper.methods.age(() => {
gateKeeper.methods.income(() => {
gateKeeper.methods.createPayload();
});
});
}
},
resources: class customer {
constructor(prospectInput, developerInput) {
this.age = prospectInput.age;
this.income = prospectInput.income;
this.maritalStatus = prospectInput.maritalStatus;
this.majorCc = prospectInput.majorCc;
this.zipCode = prospectInput.zipCode;
this.possibilities = developerInput; //MUST BE A DICTIONARY WITH ARRAY OF LOCATIONS
}
},
build(prospectInput, developersInput) {
var payload;
gateKeeper.prospect = prospectInput;
for (var i in developersInput) {
gateKeeper.settings = developersInput[i];
payload = gateKeeper.prospect;
gateKeeper.methods.packageMethods();
}
return new gateKeeper.resources(gateKeeper.prospect, gateKeeper.possibilities);
}
};
var test = gateKeeper.build(prospect, developers);
console.log(test.possibilities[1].Bluegreen[3]);

Can someone explain the use of ...spread operator in the following example? [duplicate]

This question already has answers here:
What are these three dots in React doing?
(23 answers)
Closed 3 years ago.
As per my understanding this is how spread operator works:
x=[1,2,3];
y=[...x,4,5];
// this is same as y=[1,2,3,4,5]
const initialState={
ingredients: [
new Ingredient('Apples', 5),
new Ingredient('Tomatoes', 10),
]
};
export function shoppingListReducer( state=initialState, action:ShoppingListActions.ShoppingListActions ) {
switch(action.type) {
case ShoppingListActions.ADD_INGREDIENT:
return {
...state,
ingredients:[...state.ingredients,action.payload ]
}
default:
return state;
}
Here in the above example what does
return {
...state,
ingredients:[...state.ingredients,action.payload ]
}
evaluate to?
Payload is of type Ingredient :
export class Ingredient {
constructor(public name: string, public amount: number) {}
}
Basically you are trying to create an object with all the properties of state object and overriding its property ingredients with value as all the values in state.ingredients array along with action.payload. This might be done to separate the reference of the result object from state object.
var state = {
"someprop" : "somevalue",
"ingredients" : ["a", "b"]
};
var action = {
"payload" : 4
};
var result = {
...state,
ingredients:[...state.ingredients,action.payload ]
};
state.someprop = "somevalue1"; // does not alter result object
state.ingredients.push("c"); // does not alter result object
console.log(result);
Alternatively, to understand it better, you can break that into following
var result = {...state};
result.ingredients = [...state.ingredients, action.payload];
Note: In case there is a nested object in state or an object in array, they will still continue to share the same reference.
When used inside an object think of it as object.assign. the original state is added to object, then the next thing (ingredients), overwriting anything already there if necessary (ingredients), and so on down the line

Context value getting undefined inside nested Loop

Below java-script code context value became undefined inside nested loop.but outside the nested loop the values is properly showing.
please help to show the context value inside the loop.
module.exports = function (options = {}) {
return async context => {
const { data } = context;
context.app.service('emplist').find({
query: { empId: { $in: ["12321"] } },
paginate: false,
}).then(result => {
console.log('firstname_Inside-->',context.data.firstname);
}).catch((error) => {
console.log(error);
});
console.log('firstname_Outside-->',context.data.firstname);
return context;
};
};
OUTPUT:-
//here value is undefined
firstname_Inside-->undefined
//here value is properly showing
firstname_Outside-->sam
Looks like context.app.service('emplist').find() call is asynchronous. And it affects the context. So the possible answer would be that context.data object is being cleaned up during context.app.service('emplist').find() work.

Nested Object destructuring [duplicate]

This question already has an answer here:
ES6 Object Destructuring Default Parameters
(1 answer)
Closed 6 years ago.
When destructuring objects, I sometimes run into the issue of not knowing whether or not keys exist, and then trying to pull values from them. This obviously errors, since they are undefined. For example:
Expecting something like this:
{ user: { name: { first: 'Trey', last: 'Hakanson' } } }
But I actually get this:
{ user: {} }
and attempting to destructure like this errors:
const { user: { name: { first: firstName, last: lastName } } } = data
is there any way to assign a default value earlier in the deconstruction? Such as assigning name = { first: 'Hello', last: 'World' } if the name key doesn't exist?
const { user: { name: { first: firstName = 'firstName', last: lastName = 'lastName' } = {} } = {} } = data
You can assign default values if the value is falsy value or undefined in your case. In javascript the default values can be assigned by using the || operator.
If the first operand is falsy (false, null, undefined, "",0) then it returns the second operand. Otherwise, it returns the first operand. This provides a convenient way to specify default values
var myDefaultName = name || { first: 'Hello', last: 'World' }

Categories

Resources