Only continue loop after method has finished - loops

I want the following code to run synchronous.
Each inquirer.prompt() needs to run after the other.
This is my code now:
_.forEach(diff.wrongVersion, (dependency) => {
choices = [ 'project version: ' + dependency.projectVersion, 'layer version: ' + dependency.layerVersion];
inquirer.prompt({
type: 'list',
name: 'dependencies',
message: 'Choose which version to use for ' + dependency.name,
choices
});
});
Could anybody help me with this?
I thought this could be done with Promise but I have no idea how.

You can use Array#reduce or lodash#reduce to achieve this type of sequential prompt.
diff.wrongVersion.reduce((promise, dependency) => promise.then(result =>
inquirer.prompt({
type: 'list',
name: dependency.name,
message: `Choose which version to use for: ${dependency.name}`,
choices: [
`project version: ${dependency.projectVersion}`,
`layer version: ${dependency.layerVersion}`
]
})
.then(answer => Object.assign(result, answer))
), Promise.resolve({})).then(result => {
console.log(result);
});
// =========== Mocking Inquirer Module =====================
var inquirer = {
prompt: function(question) {
var choices = question.choices
.map((v, i) => `[${i+1}] - ${v}`)
.join('\n');
var message = `${question.message}\n${choices}`;
var result = {};
var answer;
return new Promise((resolve, reject) => {
do {
answer = parseInt(window.prompt(message));
} while(
isNaN(answer) ||
answer < 1 ||
answer > choices.length ||
answer === null
);
if(answer === null) {
reject();
} else {
result[question.name] = question.choices[answer-1];
resolve(result);
}
});
}
};
const diff = {
wrongVersion: [
{
projectVersion: 'pv-1.0',
layerVersion: 'lv-1.0',
name: 'Dep-A'
},
{
projectVersion: 'pv-1.0',
layerVersion: 'lv-1.0',
name: 'Dep-B'
},
{
projectVersion: 'pv-1.0',
layerVersion: 'lv-1.0',
name: 'Dep-C'
},
{
projectVersion: 'pv-1.0',
layerVersion: 'lv-1.0',
name: 'Dep-D'
},
{
projectVersion: 'pv-1.0',
layerVersion: 'lv-1.0',
name: 'Dep-E'
},
]
};
diff.wrongVersion.reduce((promise, dependency) => promise.then(result =>
inquirer.prompt({
type: 'list',
name: dependency.name,
message: `Choose which version to use for: ${dependency.name}`,
choices: [
`project version: ${dependency.projectVersion}`,
`layer version: ${dependency.layerVersion}`
]
})
.then(answer => Object.assign(result, answer))
), Promise.resolve({})).then(result => {
console.log(result);
});

If I understand you correctly, you need the following principle:
var inquirer = {};
inquirer.prompt = function(object) {
return new Promise(function(resolve, reject) {
setTimeout(function() { // <-- here I emulate async execution
console.log('object ==> ', object);
resolve();
}, 1000);
});
}
var diff = {
wrongVersion: [{
projectVersion: 0,
layerVersion: 0,
name: 'zero'
}, {
projectVersion: 1,
layerVersion: 1,
name: 'one'
}, {
projectVersion: 2,
layerVersion: 2,
name: 'two'
}, {
projectVersion: 3,
layerVersion: 3,
name: 'three'
}]
}
var iterator = 0;
function callPrompt() {
var dependency = diff.wrongVersion[iterator];
var choices = ['project version: ' + dependency.projectVersion, 'layer version: ' + dependency.layerVersion];
inquirer.prompt({
type: 'list',
name: 'dependencies',
message: 'Choose which version to use for ' + dependency.name,
choices: choices
}).then(function() {
iterator++;
if (diff.wrongVersion[iterator]) {
callPrompt();
}
});
};
callPrompt();
Example on jsfiddle (pay attention on concole) - https://jsfiddle.net/regwtew1/2/

Related

Nested filter in typescript

I have a JSON array, which looks as follows.
[
{
id: 1,
name: 'Alex',
activity: [
{
id: 'A1',
status: true
},
{
id: 'A2',
status: true
},
{
id: 'A3',
status: false
}
]
},
{
id: 2,
name: 'John',
activity: [
{
id: 'A6',
status: true
},
{
id: 'A8',
status: false
},
{
id: 'A7',
status: false
}
]
}
]
I want to get an array of activity id whose status should be true.I can achieve this with nester for or forEach loop. But here I am looking to achieve with the help of array functions like filter, map, and some.
I have already tried with the following.
let newArr=arr.filter(a=> a.activity.filter(b=> b.status).map(c=> c.id))
But I didn't get the correct answer
Expected output
['A1','A2','A6']
function filter_activity(activities) {
return activities
&& activities.length
&& activities.map(x => x.activity)
.flat().filter(activity => activity.status)
.map(x => x.id) || [];
}
Illustration
function filter_activity(activities) {
return activities &&
activities.length &&
activities.map(x => x.activity)
.flat().filter(activity => activity.status)
.map(x => x.id) || [];
}
const input = [{
id: 1,
name: 'Alex',
activity: [{
id: 'A1',
status: true
},
{
id: 'A2',
status: true
},
{
id: 'A3',
status: false
}
]
},
{
id: 2,
name: 'John',
activity: [{
id: 'A6',
status: true
},
{
id: 'A8',
status: false
},
{
id: 'A7',
status: false
}
]
}
];
console.log(filter_activity(input));
WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET
let arr = json.flatMap(e => e.activity.filter(el => el.status).map(el => el.id))
let newArr=arr.map(x => x.activity)
.reduce((acc, val) => acc.concat(val), [])
.filter((activity:any) => activity.status)
.map((x:any) => x.id) || [];
I got error when using flat() and flatMap().So, I have used reduce().

Filter an array of object with another array - returning two values

I wanted to filter my seach by name and type when a user types on the search box however I am just getting back the names but not by type.
This is my array:
const projects = [
{
id: 1,
name: 'protfolio',
type: ['react']
},
{
id: 2,
name: 'RoboFriends',
type: ['react']
},
{
id: 3,
name: 'Background-gradient',
type: ['html ', 'css ', 'javaScript']
},
{
id: 4,
name: 'Election-map',
type: ['html ', 'css ', 'javaScript']
},
{
id: 5,
name: 'To-Do-List',
type: ['react']
}
]
The function I've reacted to filter over my array and return the project name and also type
const projectFilter = this.state.projects.filter( project => {
return project.name.toLowerCase().includes(this.state.searchField.toLowerCase())
|| project.type.includes(this.state.searchField);
})
Your code is fine. I checked. Make sure your searchField came as you wish.
Check this out
function myFunction() {
const projects = [
{
id: 1,
name: 'protfolio',
type: ['react']
},
{
id: 2,
name: 'RoboFriends',
type: ['react']
},
{
id: 3,
name: 'Background-gradient',
type: ['html ', 'css ', 'javaScript']
},
{
id: 4,
name: 'Election-map',
type: ['html ', 'css ', 'javaScript']
},
{
id: 5,
name: 'To-Do-List',
type: ['react']
}
]
const projectFilter = projects.filter( project => {
return project.name.toLowerCase().includes('react')
|| project.type.includes('react');
})
document.getElementById("test").innerText = (projectFilter[2].name);
}

why add newRecord[] is empty

I have a problem when adding a newRecord, the console always outputs [].
Please help me.
_storePR2.add(_key.data);
_storePR2.commitChanges();
var newRecord = _storePR2.getNewRecords();
console.log('newRecord',newRecord);
Output: newRecord []
enter image description here
this my store code and model :
Ext.define('Sasmita.store.vending.purchase.Purchasegoodrec', {
extend: 'Ext.data.Store',
requires: [
'Ext.data.proxy.Ajax',
'Ext.data.reader.Json',
'Ext.data.Field'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
autoLoad: false,
storeId: 'vending.purchase.Purchasegoodrec',
proxy: {
type: 'ajax',
url: 'jsonresult/Sasmita_Vending_Purchase/getPurchaseGoodrec',
reader: {
type: 'json',
root: 'data',
idProperty: 'sitecode2'
}
},
fields: [
{
name: 'purchase_id_tr'
},
{
name: 'parent_id'
},
{
name: 'file_ext'
},
{
name: 'file_name'
},
{
name: 'file_size'
},
{
name: 'description'
},
{
name: 'id'
},
{
name: 'id_file'
},
{
name: 'id_po'
},
{
name: 'qty_hasil'
},
{
name: 'no_pr'
},
{
dateFormat: 'Ymd',
name: 'date_pr',
type: 'date'
},
{
name: 'warehouse'
},
{
name: 'warehouse_name'
},
{
name: 'row_created_by'
},
{
name: 'row_created_datetime'
},
{
name: 'row_changed_by'
},
{
name: 'row_changed_datetime'
},
{
name: 'title'
},
{
name: 'notes'
},
{
name: 'qty_order'
},
{
name: 'no_po'
},
{
name: 'date_po'
},
{
name: 'supplier'
},
{
name: 'package'
},
{
name: 'qty_approve'
},
{
name: 'purchase_product_name'
},
{
name: 'unit'
},
{
name: 'unit_price'
},
{
name: 'total_price'
},
{
name: 'total_price_head'
},
{
name: 'vat'
},
{
name: 'net_price'
},
{
name: 'sum_total'
}
]
}, cfg)]);
}
});
and this my controller action button choose :
var me = this;
var _panel = me.getMainPanel();
var _tabpanel = _panel.down('#tabmaintain');
var _activetab = _tabpanel.getActiveTab();
var _window = button.up('window');
var _grid = _window.down('grid');
//var _girdd = this.getPanelSearch();
//var _grids = _girdd.down('grid');
var _gridSelected = _grid.getSelectionModel().getSelection();
//var row = _grid.store.indexOf(_gridSelected);
//console.log(row);
console.log(_gridSelected);
console.log(_grid);
//console.log(_girdd.down('grid'));
//selected=[];
//Check selected product
if(_gridSelected.length===0){
Ext.Msg.alert('Warning','Please select product');
return;
}
//Submit Product
var _gridPR = _activetab.down('#detailProduct');
var _storePR2 = _gridPR.getStore();
//console.log(_storePR2.data);
Ext.Array.each(_gridSelected,function(_key,_value,item){
//console.log(selected.push(item));
_validate = true;
_storePR2.each(function(_storeData,_storeIndex){
console.log(_key.data);
if(_storeData.data.no_po === _key.data.no_po){
_validate = false;
Ext.Msg.alert('Warning','The Product had been picked');
return;
}
});
if(_validate){
// Add record to the store by data
_storePR2.add(_key.data);
// Get array of new records from the store
var newRecords = _storePR2.getNewRecords();
console.log('newRecord',newRecords);
// Commit changes after getting new records
_storePR2.commitChanges();
_window.close();
}
});
That is because you committed the changes, so there are no longer any 'new records'.
Try to get the new records before committing the changes:
// Add record to the store by data
_storePR2.add(_key.data);
// Get array of new records from the store
var newRecords = _storePR2.getNewRecords();
console.log('newRecord',newRecords);
// Commit changes after getting new records
_storePR2.commitChanges();
Here is a fiddle.
First you need to add records to store and commit changes,then get new records.
grid_store.add({'Name':"ab",'dob':"099"})
grid_store.commitChanges();
var newRecord = grid_store.getNewRecords()
console.log('newRecord',newRecord);
});
Here is a fiddle: http://jsfiddle.net/2p78md5t/3/

Angular 2 loop through a list with some delay

How do I loop through an array with some delay with Angular 2 and TypeScript?
I have an array,
students: Array<any> = [
{
name: "Alan"
},
{
name: "Jake"
},
{
name: "Harry"
},
{
name: "Susan"
},
{
name: "Sarah"
},
{
name: "Esther"
}
];
I want to loop through the list and display the names with a 2000ms delay.
<div *ngFor="let student of students">
{{student.name}}
</div>
doesn't work with a delay but is looping all at once.
Just use setTimeout. For example (* not tested):
students: Array<any> = [ ];
populateArrayWithDelay():void{
let people = [
{
name: "Alan"
},
{
name: "Jake"
},
{
name: "Harry"
},
{
name: "Susan"
},
{
name: "Sarah"
},
{
name: "Esther"
}
];
for(let i = 0; i < people.length; i++){
let student = people[i];
setTimeout(() => {
this.students.push(student);
}, 2000*(i+1));
}
}
Plunker example
export class App {
name:string;
students: Array<any> = [
{
name: "Alan"
},
{
name: "Jake"
},
{
name: "Harry"
},
{
name: "Susan"
},
{
name: "Sarah"
},
{
name: "Esther"
}
];
constructor() {
var timer = 0;
this.$students = Observable.from([[], ...this.students])
.mergeMap(x => Observable.timer(timer++ * 1000).map(y => x))
.scan((acc, curr) => {acc.push(curr); return acc;});
}
}

How to access method in controller from another in angularjs

How can i access a method in tableController from my menuController. Here is my code.i want to call addRow() method from select() in menu controller. these controllers are in different modules.Please Help me.
my menu controller
var menuApp = angular.module('menuApp', []);
menuApp.controller('menuController', ['tableService', function ($scope, tableService) {
$scope.menuItem = [
{
id: 1,
title: "new",
navigate:"N",
child: [{
id: 11,
title: "new11",
navigate: "N",
child: [{
id: 12,
title: "new12",
navigate: "Y",
url:"/Home/index"
}]
}]
},
{
id: 2,
title: "new",
child: [{
id: 21,
title: "new21",
child: [{
id: 22,
title: "new22"
}]
}]
}
];
$scope.select = function (data) {
if (data.navigate == "Y") {
alert(data.url);
tableService.add();
}
}
}]);
my table controller
tableApp.controller('tableController', function ($scope, $rootScope, $filter, $uibModal) {
$scope.filteredPeople = [];
$scope.currentPage = 1;
$scope.pageSize = 10;
$scope.people = [{ id: "1", name: "joe",disable:true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true },
{ id: "1", name: "joe", disable: true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true },
{ id: "1", name: "joe", disable: true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true },
{ id: "1", name: "joe", disable: true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true },
{ id: "1", name: "joe", disable: true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true }];
$scope.addRow = function () {
debugger;
$scope.people.unshift({
id: "",
name: "",
disable:false
});
$scope.getPage();
}
$scope.getPage = function () {
var begin = (($scope.currentPage - 1) * $scope.pageSize);
var end = begin + $scope.pageSize;
$scope.filteredPeople = $filter('filter')($scope.people, {
id: $scope.idFilter,
name: $scope.nameFilter
});
$scope.totalItems = $scope.filteredPeople.length;
$scope.filteredPeople = $scope.filteredPeople.slice(begin, end);
};
$scope.getPage();
$scope.pageChanged = function () {
$scope.getPage();
};
$scope.open = function () {
$scope.id = generateUUID();
};
$scope.dblclick = function (index) {
for (var i = 0; i < $scope.filteredPeople.length; i++) {
$scope.filteredPeople[i].disable = true;
}
return index.disable = false;
}
$scope.rowSelect = function (rowdata) {
alert(rowdata.name);
}
$scope.openInput = function (index) {
debugger;
var modalInstance = $uibModal.open({
templateUrl: '/Home/index',
controller: 'testController',
resolve: {
items: function () {
return index;
},
cat: function () {
return 'Account';
}
}
});
}
});
Example of a service shared between controllers & directives
/**
* store and share data between controllers & directives
*/
angular.module('interfaceApp').service('shareData', function () {
this.datas = [];
this.add = function (data) {
this.datas.push(data);
};
//retourne l'élément correspondant à la clé ( utilise la date comme clé )
this.getElement = function (key) {
......
return ;
};
this.getDatas = function () {
return this.datas;
};
});
/* Controller */
var searchModule = angular.module('searchModule', []);
// inject the service in the controller
.controller('searchCtrl', function ($scope, shareData ) {
shareData.add( ... );
console.log( shareData.getDatas() );
});
A service is a singleton, so all controllers using it acces to the same datas ( when they call shareData.getDatas() )

Resources