var listOfItems = [1, 2, 3, 4, 5];
listOfItems.forEach(
item => {
this.createTimeout(3000)
.then(
() => {
console.log(item);
})
});
createTimeout(timeout) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(null),timeout)
}) }
I want to wait for Promise response 'createTimeout' and then move to next element. Any ideas ?
Related
electron not provide data to renderer process but provide it in preload
preload.js //
contextBridge.exposeInMainWorld(
'tintacle', {
async supportStatus() {
await ipcRenderer.invoke('supportStatusHandler').then(status => console.log(status)) // here i getting right status
}
}
)
main.js //
let microSipPromise = new Promise((resolve, reject) => {
let findPath = spawn('powershell.exe', ['get-process microsip | select-object -ExpandProperty Path']); // find MicroSip path
findPath.stdout.once('data', (data) => {
exePath = iconv.decode(data, '866');
currentSupportStatus = 'online';
resolve('online')
})
findPath.stderr.once('data', (data) => {
currentSupportStatus = 'offline';
dialog.showMessageBox({message: 'Запустите MicroSip', type: 'warning', title: 'Warning!'})
resolve('offline')
})
})
ipcMain.handle('supportStatusHandler', () => {
return microSipPromise
})
And on front i get undefined, here is call of preload func
renderer
window.tintacle.supportStatus().then(status => console.log(status))
You need to return the promise in supportStatus:
supportStatus: () => ipcRenderer.invoke('supportStatusHandler')
I am currently using #react-native-community/cameraroll currently and i am trying to get images and albums on my ios device.
The following is the code I tried
CameraRoll.getPhotos({})
.then((res) => {
console.log("result 1", res)
}).catch((error) => { })
CameraRoll.getAlbums({})
.then((res) => {
console.log("result 2", res)
})
.catch((error) => {
console.log(error);
});
result 1 and result 2 give the following result
result 1 {"edges": [], "page_info": {"has_next_page": false}}
result 2 []
Any help would be appreciated. The same code works well on Android.
I tried with a lot of combinations and the one below worked for the ios device -
CameraRoll.getPhotos({ first: 5000, assetType: 'Photos' })
.then((result) => {
const tempBuckets = [];
var edgesArr = result.edges;
}).catch((error) => { })
The result here contains an edges array that has all the images and their respective properties.
The count '5000' is an arbitrary number i have used, without which the result array obtained was empty.
the solution is to add permission before request like
async function hasAndroidPermission() {
const permission =
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE;
const hasPermission = await PermissionsAndroid.check(permission);
if (hasPermission) {
return true;
}
const status = await PermissionsAndroid.request(permission);
return status === 'granted';
}
and use like this
const Gallery = async () =>{
if (Platform.OS === "android" && !(await hasAndroidPermission())) {
return;
}
CameraRoll.getAlbums({assetType: "Photos", albumType: "All"})
.then((r:any) => {
console.log("images-->",r)
})
.catch((err:any) => {
//Error Loading Images
console.log("err->",err)
});
}
I have been stuck with this for a bit. I need to test a website and I need to post info in order to test if it appears on the page.
What I have so far is this
(async () => {
const browser = await webkit.launch();
const page = await browser.newPage();
await page.route('http://100.100.100.100/', route => route.fulfill({
status: 200,
body: body,
}));
await page.goto('https://theurlofmywebsite/');
await page.click('button')
await page.click('text=Login with LoadTest')
await page.fill('#Username','username')
await page.fill('#Password','password')
await page.click('#loginButton')
// await page.waitForSelector('text=Dropdown');
await page.click('css=span >> text=Test')
await page.click('#root > div > div > header > ul.nav.navbar-nav.area-tabs > li:nth-child(6) > a','Test')
await page.waitForSelector('text=Detail')
await page.screenshot({ path: `example3.png` })
await browser.close();
})();
const body = [ my json post request ]
jest.setTimeout(1000000);
let browser: any;
let page: any;
beforeAll(async () => {
browser = await chromium.launch();
});
afterAll(async () => {
await browser.close();
});
beforeEach(async () => {
page = await browser.newPage();
});
afterEach(async () => {
await page.close();
});
it("should work", async () => {
await fetch("http://YOUAWESOMEURL", {
method: "post",
body: JSON.stringify(body),
})
.then((response) => console.log(response))
.catch((error) => console.log(error));
await page.goto("https://YOUAWESOMEURL");
await page.click("button");
await page.click("text=Login");
await page.fill("#Username", "YOURUSERNAME");
await page.fill("#Password", "YOURPASSWORD");
await page.click("#loginButton");
// await page.click("css=span >> text=Load Test");
await page.click(
"#root > div > div > header > ul.nav.navbar-nav.area-tabs > li:nth-child(6) > a >> text=Test"
);
await page.waitForSelector("text=SOMETEXTYOUWANTTOCHECKIFTHERE");
// await page.waitForSelector(`text=SOMEOTHERTEXTYOUWANTTOCHECKIFTHERE`);
// Another way to check for success
// await expect(page).toHaveText(`SOMEOTHERTEXTYOUWANTTOCHECKIFTHERE`);
console.log("test was successful!");
});
With 1.19 version it looks easy.
test('get respons variable form post in Playwright', async ({ request }) => {
const responsMy= await request.post(`/repos/${USER}/${REPO}/issues`, {
data: {
title: '[Bug] report 1',
body: 'Bug description',
}
});
expect(responsMy.ok()).toBeTruthy();
}
See more on https://playwright.dev/docs/test-api-testing
import { expect, request } from '#playwright/test';
const baseApiUrl = "https://api.xxx.pro/node-api/graphql";
test('API Search', async ({ request }) => {
const search_query = `query {me { id username}} `;
const response = await request.post(baseApiUrl, {
data: {
query: search_query
},
headers: {
authorization: `Bearer eyJhbGciOiJIUzcCI6IkpXVCJ9.eyJzd`
}
});
const bodyResponse = (await response.body()).toString();
expect(response.ok(), `${JSON.stringify(bodyResponse)}`).toBeTruthy();
expect(response.status()).toBe(200);
const textResponse = JSON.stringify(bodyResponse);
expect(textResponse, textResponse).not.toContain('errors');
});
I have a kendo grid on my razor view mvc as below:
#(Html.Kendo().Grid(Model.employeeList)
.Name("grid")
.Pageable(pager => pager
.Messages(messages => messages.Empty("No data"))
)
.Pageable(pager => pager
.PageSizes(new[] { 15, 20, 25, 50 })
)
.Filterable()
.Groupable()
.Sortable()
.Columns(columns =>
{
columns.Bound(employee => employee.employeeId);
columns.Bound(employee => employee.firstName);
columns.Bound(employee => employee.lastName);
columns.Bound(employee => employee.jobTitle);
columns.Bound(employee => employee.employeeId).ClientTemplate(
"<a href='" + Url.Action("Edit", "Employee", new { id = "#=employeeId#" }) + "'>Edit</a> | " +
"<a href='" + Url.Action("Details", "Employee", new { id = "#=employeeId#" }) + "'>Details</a> | " +
"<a href='" + Url.Action("Delete", "Employee", new { id = "#=employeeId#" }) + "'>Delete</a>"
)
.Filterable(false)
.Groupable(false)
.Sortable(false)
.Title("");
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetEmployeesList", "Employee").Data("branchData")).PageSize(15)
)
)
Along with the controller for GetEmployeesList ActionResult:
[HttpPost]
public ActionResult GetEmployeesList([DataSourceRequest]DataSourceRequest request, int branchId, bool includeNonActive)
{
IQueryable<Employee> employees;
if (includeNonActive)
{
employees = db.Employee.Where(e => e.branchId == branchId && e.isDeleted == false)
.Include(e => e.HireType).Include(e => e.HireStatus);
}
else
{
employees = db.Employee.Where(e => e.branchId == branchId && e.HireStatus.hireStatusId == 1 && e.isDeleted == false)
.Include(e => e.HireType).Include(e => e.HireStatus);
}
DataSourceResult result = employees.ToDataSourceResult(request, employee => new EmployeeViewModel
{
employeeId = employee.employeeId,
firstName = employee.firstName,
lastName = employee.lastName,
jobTitle = employee.jobTitle,
HireStatus = new HireStatus() { hireStatus = employee.HireStatus.hireStatus },
HireType = new HireType() { hireType = employee.HireType.hireType }
});
return Json(result);
}
So far, everything went well. DataSourceRequest request was passed from the grid successfully.
But then I have another post AJAX call via jQuery:
$(document).ready(function () {
$('#ddlBranchList').change(function () {
var isNonActive = $('#isNonActive')[0].checked;
var ddlValue = $('#ddlBranchList').val();
$.ajax({
type: "POST",
url: "/Employee/GetEmployeesList",
data: JSON.stringify({ branchId: ddlValue, includeNonActive: isNonActive }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
resultData = result;
},
error: function () {
alert("Error retrieving Employees List!");
}
}).done(function () {
var dataSource = new kendo.data.DataSource({
data: resultData.Data,
pageSize: 15
});
var grid = $('#grid').data("kendoGrid");
grid.setDataSource(dataSource);
dataSource.read();
});
});
}
A dropdown change event should trigger an ajax post to the controller, but I couldn't properly pass a proper object to DataSourceRequest request parameter. When it is posted, DataSourceRequest request is always null.
How do I pass the object correctly?
I got it working by forcing the kendo grid to re-read the data:
$('#ddlBranchList').change(function () {
var grid = $('#grid').data("kendoGrid");
grid.dataSource.read();
});
and then modify the branchData function:
function branchData() {
var isNonActive = $('#isNonActive')[0].checked;
var ddlValue = $('#ddlBranchList').val();
if (ddlValue > 0) {
branchId = ddlValue;
}
return {
branchId: branchId,
includeNonActive: isNonActive,
}
}
loadFont() {
return new Promise((resolve, reject) => {
this.FontLoader.load(
fontParams.url,
(response) => {
console.log('loadfont')
this.font = response
this.createTextMaterials()
this.createNumberList()
console.log('loadfont')
resolve(response)
}, (xhr) => {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
}, (err) => {
console.log(err)
})
})
}
it worked on android,but not on IOS,i test it on iphone5 and iphone6.
the debugging Always display:"request begin"
i print the err:
{"target":{"onabort":null, "onloadstart":null, "ontimeout":null,
"onloadend":null, "onreadystatechange":null, "readyState":1,
"response":null, "responseText":null, "responseType":"",
"responseXML":null, "status":0, "statusText":"", "upload":{},
"withCredentials":false}}
err mseeage