Shouldn't async functions always execute as the last ones? [duplicate] - javascript

This question already has answers here:
Are javascript's async functions actually synchronous?
(2 answers)
When does async function actually return a pending promise?
(1 answer)
Closed 18 days ago.
What's happening here?? the order of execution is commented.
dad() is async and returns a promise. shouldn't it be executed after console.log('faster')?
two() is async w/o await and still it's executes before console.log(5)
g() is awaited and executes as the last one?!
async function dad(){
    async function g(){
    return new Promise((a,b)=>{
    setTimeout(() => {
        console.log('im waiting') //4th
        }, 2000)
        a(6)
    })
    }
    async function two(){
        console.log(2) //1st
    }
    two()
    await g()
    console.log(5) //3rd
}
dad()
console.log('faster') //2nd

Related

autocomplete form in django

i'm trying to make an autocomplete form in django but when i run the page locally don´t run because don't find the url of the json, the idea of the autocomplete is that take information from x table and then the form post the information in y table
views.py
def is_ajax(request):   
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'def
get_employee(request):   
if is_ajax(request=request):       
q = request.GET.get('term', '')       
places = InfoTrabajadores.objects.filter(documento__icontains=q)       
results = []       
for pl in places:           
place_json = {}           
place_json['label'] = pl.state           
results.append(place_json)       
data = json.dumps(results)   
else:       
data = 'fail'   
mimetype = 'application/json'   
return HttpResponse(data, mimetype)
and the jquery
$(document).ready(function() {
async function getCities(event, ui) {
//let url = '{% url ' / api / get_employees / ' %}';
let url = 'http://127.0.0.1:8000/api/get_employees/';
let results = await fetch(url);
let data = await results.json();
return data;
};
async function AutoCompleteSelectHandler(event, ui) {
let zipCode = await getCities();
$('#nombre').val(nombre[ui.item.value]);
$('#num_emergencia').val(num_emergencia[ui.item.value]);
$('#prov_salud').val(prov_salud[ui.item.value]);
$('#prov_salud_trabj').val(prov_salud_trabj[ui.item.value]);
$('#rh').val(rh[ui.item.value]);
};
$("#autoSuggest").autocomplete({
source: "{% url 'invitados' %}",
select: function(event, ui) {
AutoCompleteSelectHandler(event, ui)
},
minLength: 2,
});
});

NodeJS Cucumber test are executed with not wait

My test fails. The test is executed immediately, and the automation test doesn't wait to finish some of the actions.
I saw an issue with cucumber and nodejs, but I am unsure how to handle it.
Here is my step js class:
const { Given, When, Then } = require('#cucumber/cucumber');
Given("I visit the automation-practice-form page", async () => {
    await page.goto("https://demoqa.com/automation-practice-form/");
});
When("I fill the form with correct data", async () => {
  await page.fill('#firstName', 'Tester');
    await page.fill('#lastName', 'Testerov');
    await page.fill('#userEmail', 'testingemail#testemail.com');
    await page.check('//*[#id="gender-radio-1"]/following-sibling::label');
    await page.fill('#userNumber', '1232131231');
    await page.click("#dateOfBirthInput");
    await page.click('(//div[#role="option"])[1]');
    await page.fill('#subjectsInput', 'Computer Science');
    await page.keyboard.press("Enter");
    await page.click('//*[#id="hobbies-checkbox-1"]/following-sibling::label');
    await page.setInputFiles("#uploadPicture", "uploads/test-image.jpg");
    await page.fill('#currentAddress', 'Test Address');
    await page.click("#state");
    await page.click('//*[#id="react-select-3-option-1"]', { force: true });
    await page.click("#city");
    await page.click('//*[#id="react-select-4-option-0"]');
});
When("click over the Submit button", async () => {
    await page.click("#submit");
});
Then("I will verify that the data ware filled in correctly", async () =>  {
    let name_actualResultElement = page.locator(
        '//*[contains(text(),"Student Name")]/following-sibling::td'
    );
});
and feature class:
Feature: Fill the form
    As a user
    I want to be able to fill the form
    Scenario: Fill the form with valid data
        Given I visit the automation-practice-form page
        When I fill the form with correct data
        When click over the Submit button
        Then I will verify that the data ware filled in correctly

How to call php function if javascript condition true

I have create some personal project with wordpress + php + google firebase.
I want to execute function if Google firebase OTP verification is success.
Here is the code
function devsol_customer_form() { ?>
<form>
<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
<label for="number"><?php esc_html_e( 'Mobile Number', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="tel" class="woocommerce-Input woocommerce-Input--text input-text" name="number" id="number"/>
</p>
<div id="recaptcha-container"></div>
<button class="woocommerce-Button button woocommerce-form-login__submit" type="button" onclick="phoneAuth();">SendCode</button>
</form>
<br/>
<h1>Enter Verification code</h1>
<form>
    <input type="text" id="verificationCode" placeholder="Enter verification code" class="woocommerce-Input woocommerce-Input--text input-text">
    <button class="woocommerce-Button button woocommerce-form-login__submit" type="button" onclick="codeverify();">Verify code</button>
</form>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#config-web-app -->
<script>
    // Your web app's Firebase configuration
    var firebaseConfig = {
    apiKey: "*****",
    authDomain: "*****",
    databaseURL: "*****",
    projectId: "*****",
    storageBucket: "*****",
    messagingSenderId: "*****",
    appId: "*****"
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
</script>
<script>
window.onload=function () {
  render();
};
function render() {
    window.recaptchaVerifier=new firebase.auth.RecaptchaVerifier('recaptcha-container');
    recaptchaVerifier.render();
}
function phoneAuth() {
    //get the number
    var number=document.getElementById('number').value;
    //phone number authentication function of firebase
    //it takes two parameter first one is number,,,second one is recaptcha
    firebase.auth().signInWithPhoneNumber(number,window.recaptchaVerifier).then(function (confirmationResult) {
        //s is in lowercase
        window.confirmationResult=confirmationResult;
        coderesult=confirmationResult;
        console.log(coderesult);
        alert("Message sent");
    }).catch(function (error) {
        alert(error.message);
    });
}
function codeverify() {
    var code=document.getElementById('verificationCode').value;
    coderesult.confirm(code).then(function (result) {
        alert("Successfully registered");
        var user=result.user;
        console.log(user);
    }).catch(function (error) {
        alert(error.message);
    });
}    
</script>
<?php }
add_action('woocommerce_after_customer_login_form', 'devsol_customer_form');
I want if user successfully verify the OTP then this function call in my php file. I am using function.php file in my wordpress theme.
function devsol_customer_auth() {
$user_phone = sanitize_text_field( $_POST['number'] );
if ( $user = get_user_by( 'login', $user_phone) ) {
$user_id = $user->ID;
$user_roles = $user->roles;
$user_role = array_shift($user_roles);
if ( $user_role === 'customer') {
if ( apply_filters( 'woocommerce_registration_auth_new_customer', true, $user_id ) ) {
wc_set_customer_auth_cookie( $user_id );
}
}
}
}
add_action('init', 'devsol_customer_auth');
Someone please help
You cannot directly call php function from javascript(JS) as JS runs on the client side like on the browser and your php file exists on the webserver.
In order to do something like that, you'll need to make request to the php file and pass parameter in the request(could be GET or POST).
A simple example of such could be
create a separate php file, lets say actions.php, that will be hit by the request.
make a request to the file from JS
E.g.
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
httpGet('www.yourSite.com/actions.php?phone=' + userPhoneNumber);
This should resolve your problem.

Assigning an ajax fetch function to a variable returns undefined even though data definitely returns?

I have a data fetch function getAvailableDates that I call by assigning a variable AVAILABLE_DATES, in the done callback I log out the response and my data is there but returning the data and logging out the variable returns undefined. Can anyone explain where I might be going wrong with this?
define([
'jquery'
], function (
$
) {
"use strict";
function getAvailableDates() {
console.log('Running getAvailableDates');
var requestAvailableDates = $.ajax({
type: "GET",
url: 'api/dcgdates',
data: JSON.stringify(requestAvailableDates),
dataType: "json",
contentType: "application/json"
});
requestAvailableDates.done(function(data) {
console.log('getAvailableDates success', data);
return data;
});
}
return {
DATE_FORMAT: "dd M yy",
AVAILABLE_DATES: getAvailableDates()
};
});
Use the deferred return by the $.ajax, as you use it to log the data, its chainable, you can write:
var request = $.ajax(...);
// This will return the deferred object. And you can keep call `.done` on it to chain the callbacks.
return request.done(...).done(...);
All of the callbacks chained by .done will receive the same data from your ajax request.
define(['jquery'], function($) {
"use strict";
function getAvailableDates() {
console.log('Running getAvailableDates');
var requestAvailableDates = $.ajax({
type: "GET",
url: 'api/dcgdates',
data: JSON.stringify(requestAvailableDates),
dataType: "json",
contentType: "application/json"
});
// Return a deferred object.
return requestAvailableDates.done(function(data) {
console.log('getAvailableDates success', data);
return data;
});
}
return {
DATE_FORMAT: "dd M yy",
deferredObj: getAvailableDates()
};
});
Then you can get the object and use :
returnObj.deferredObj.done(function(data) {
// do something......
});
To get its value.
Below is a snippet to show how you can use it.
var test = function() {
var dfd = $.Deferred();
setTimeout(function() {
dfd.resolve(1);
}, 3000);
// Each .done returns the deferred object, which can be chained to more callbacks.
// And they'll execute in the order you chained them.
return dfd
.done(function(val) {
console.log(val);
})
.done(function(val) {
console.log('another ' + val);
});
};
var deferred = test();
// The return deferred object can keep chaining to get the value.
// You can write your logic here to handle the data when deferred resolved.
deferred.done(function(val) {
console.log('I got the same value: ' + val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

JQuery catch any ajax error

i like to catch any ajax 401 Unauthorised exception, but do no like to change all my ajax queries. Is there a way to change it for any $.ajax call like (overwrite any error handler) ?
you can use the global ajax event handlers .ajaxError()
$( document ).ajaxError(function( event, jqxhr, settings, exception ) {
    if ( jqxhr.status== 401 ) {
        $( "div.log" ).text( "Triggered ajaxError handler." );
    }
});
You can do something like this:
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 401) {
alert('HTTP Error 401 Unauthorized.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
This will catch error in any of your ajax calls.
The $.ajaxSetup() function will allow you to specify global options for Ajax calls. Be careful however as other calls to ajaxSetup() will overwrite global options and specified local options to the ajax() method will override global settings.
Documentation
Try using .ajaxError() as a global method http://api.jquery.com/ajaxError/
To catch a 401 status code simply add
$.ajaxSetup({
statusCode: {
401: function(err){
console.log('Login Failed.', err.responseJSON);
// or whatever...
}
}
});
to your page somewhere before the AJAX call is fired.

Categories