We help IT Professionals succeed at work.

JavaScript

123K

Solutions

42K

Contributors

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and  in almost every mainstream web browser.

This is an MVC 5 project. I am having a problem getting a second view to be shown from a parent view. My parent view is a purchase order which has line items. The line items are to be added by launching a second view from the parent view. Both views use the same controller but each has their own action method. I use the below JavaScript from the PurchaseOrder view to pass data to PurchaseOrderAddItem view (child view):

$(document).ready(function () {
        $('#PurchaseOrderLineItemAddId').click(function () {
            var aPurchaseOrderViewModel = @Html.Raw(Json.Encode(Model));    
            var selectedVendorText = $('#ddlvendors option:selected').text();
            var selectedVendorValue = $('#ddlvendors option:selected').val();  
            var LineItemReqJsonObj = {};

            LineItemReqJsonObj.PurchaseOrderId = aPurchaseOrderViewModel.PurchaseOrderId;
            LineItemReqJsonObj.VendorText = selectedVendorText;
            LineItemReqJsonObj.VendorValue = selectedVendorValue;

            var dataToPass = '{aLineItemReqJsonObj: ' + JSON.stringify(LineItemReqJsonObj) + '}';

                $.ajax(
                    {
                        type: "POST",
                        //data: '{ aPurchaseOrderViewModel: ' + JSON.stringify(aPurchaseOrderViewModel) + ' }',
                        //data: aPurchaseOrderViewModelStr,
                        data: dataToPass,
                        url: '@Url.Action("PurchaseOrderAddItem")',
            

Open in new window

0
Hi Experts

Could you point why a Laravel Controller method produces an error when another similar runs correctly?

Accordingly to:

JS
function Vitrine() {}
 

//OK
Vitrine.prototype.salvar = function(){
  
  $.ajax({
    url: '/vitrine/salvar',
    
    method: "POST",
    data: {
      _token: $('input[name="_token"]').val(),
      id: $('#id').val(),
      url: $('#url').val(),
      inicio: $('#inicio').val(),
      termino: $('#termino').val(),
      title: $('#title').val(),
      description: $('#description').val(),
      points: $('#points').val()
    },
    error:function(data){
      hotsite.openModalCustom("Erro", data.responseText, "Entendi", "error");
    },
    success: function(data){
      hotsite.openModalCustom("Sucesso ao salvar", data.retorno, "Entendi", "success");
      hotsite.closeModal('mEditor');
      //hotsite.vitrine.filtrar();
    }
  });
};


// This doesn't runs correctly
Vitrine.prototype.minhasfotos = function(){
  $.ajax({
    url: '/vitrine/minhasFotos',
    method: "GET",
    dataType: "html",
    error:function(data){
      hotsite.openModalCustom("Erro", "Erro ao carregar vitrine.", "Entendi", "error");
    },
    success: function(data){
      $('#midiaList').html(data);
    }
  });
}

Open in new window



Laravel routes:
Route::post('/vitrine/salvar',['uses'=>'VitrinesController@salvar'])->middleware('cadastro');   // OK
Route::post('/vitrine/minhasfotos',['uses'=>'VitrinesController@minhasFotos'])->middleware('cadastro');  //NOK

//This route apparently is called somehow....
Route::get('/vitrine/{id}/obter',['uses'=>'admin\VitrineController@obter'])->middleware('cadastro');

Open in new window



VitrinesController methods:

Open in new window

0
Hi Experts


Could you point how to configure this Bootstrap buttons to be correctly distributed accordingly with this layout?

img010

<div class='row'>

      <div class="panel panel-primary">
      
          <div class='row'>
          
            <div class='col-md-8 pull-right'>
              <div class="btn-group" role="group">
                <button type="button" class="btn btn-primary" onclick="hotsite.vitrine.novo();">
                  <i class="fas fa-video" aria-hidden="true"></i> Minhas Fotos
                </button>
              </div>
            </div>
            
            <div class='col-md-6 pull-right'>
              <div class="btn-group" role="group">
                <button type="button" class="btn btn-primary" onclick="hotsite.vitrine.novo();">
                  <i class="fas fa-video" aria-hidden="true"></i> Todas as Fotos
                </button>
              </div>
            </div>
              
            <div class='col-md-4 pull-right'>
              <div class="btn-group" role="group">
                <button type="button" class="btn btn-primary" onclick="hotsite.vitrine.novo();">
                  <i class="fas fa-video" aria-hidden="true"></i> Enviar Foto
                </button>
              </div>
            </div>
              
          </div>  
       
    </div>
</div>

Open in new window


Thanks in advance!
0
Here's my code:

$(window).on('user-form-show', function(e, userId, opts){
    // prep the modal
    $uModal.find('.loading').show();
    $uModal.find('.main').hide();

    // show the modal loading screen
    $.magnificPopup.open({
      alignTop: true,
      items: {
        src: $uModal, // can be a HTML string, jQuery object, or CSS selector
        type: 'inline'
      }
    });

    // clear the cached data
    data = {};

    // clear the form from any previous data
    clearForm();
           

    // load the data if a valid id is provided
    if (typeof userId != 'undefined' && userId != 'new') {
      loadFormData(userId);
    } else {
      // set the id for a new user
        loadedUserId = 'new';
        // load drag & drop members 
        teamDragula(userId);

        $form.find('#user-role').attr('data-user-id', loadedUserId);
      // force the password fields
      $form.find('.btn-change-password').replaceWith( $passwordForm.clone() );
      $form.find('.btn-cancel-password').closest('.col').remove();

      // show the form
      $uModal.find('.loading').hide();
      $uModal.find('.main').show();
    }
  });

Open in new window


My question is this:

In the first line, you have this:

  $(window).on('user-form-show', function(e, userId, opts){

How needful is the "e" character?

From what I can gather, under the hood in every Event Handler, the "event object" is being passed into the function as an argument. I've seen this a lot with "event.preventDefault."

Thing is, how necessary is it? The reason I ask is because you don't see "e" all the time, and yet it seems like it's always there in the background even it if's not being coded as such.

Is that correct?

Is the event object (e) always assumed even if it's not being included as part of the syntax?

Could I just as easily write the above code as $(window).on('user-form-show', function(userId, opts)?

Thanks!
0
Hi Team,
 
I build a page where one drop down is there in drop down all weeks days are coming while selecting the date all days only enable in date picker . suppose we select Monday from drop down then in date picker  only all Mondays are enable to select other days are disable .

now my requirement is that in place of days we select month from drop down then only that particular month is enable on date picker other months are disable to select .


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet"
	href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function ()
	    {
	        //datepicker
	        $("#txtstart_date").datepicker
	        ({
	            minDate:"dateToday",
	            dateFormat: 'dd-mm-yy',
	            changeMonth: true,
	            numberOfMonths: 1,
	            onClose: function (selectedDate) {
	                $("#txtend_date").datepicker("option", "minDate", selectedDate);
	            },
	            //Code to disable dates according to selection
	            beforeShowDay: filterDate
	        });
	    });
	    //By default no day selected in dropdown. So all the days will be 

Open in new window

0
Hi Experts


Could you point what's needed to change from video upload to image/photo upload on this view?

Accordingly to this code:

<div id='box-video' class='col-md-5 text-center'>

	<video controls style='width: 100%'>
		<source id='srcVitrine' src='' />
	</video>
	
	// Change to:
	<img controls style='width: 100%'>
		<source id='srcVitrine' src='' />
	</img>
	

	<div class='col-md-12 form-group'>
		<label for='titulo'>URL (Vídeo):</label>
		<div class="input-group">
			<input type='text' id='url' name='url' disabled class='form-control'/>
			<span class="input-group-btn">
				<button class="btn btn-primary" type="button" onclick='hotsite.vitrine.subirVideo();'><i class="fa fa-camera"></i></button>
			</span>
			<input type='file' id='file' name='file' style='display:none;'/>
		</div>
	</div>
</div>


<script>
  var jqXHRData;
  $(document).ready(function() {

    
    var pars = {
        _token:$('input[name="_token"]').val()
    };

    var resultImageUpload = function (data) {
        if (!data.result.erro) {
            localizacao = data.result.retorno.localizacao;
            $('#url').val(localizacao);
            $('#srcVitrine').attr('src', localizacao);
            
			
			// This runs
			$("#box-video video")[0].load();
			
			// This doesn't run
            $("#box-video img")[0].load();
					
            return false;
        } else {
          hotsite.openModalCustom("Erro",'Erro ao subir vídeo.', "Entendi", "error");
          return false;
 

Open in new window

0
Hi,
I'm trying to figure out how to change the current code which originally only took a single key ("offerType") and used the "addToLookupTable" function to identify and add the associated value into the existing sTags1 array. What I want to do now is have the code check my values passed via the "addToLookupTable" function and if all the values in the  "addToLookupTable"  call exist in the current values being passed in the  _dtmPixelMapping function, then it is added to the sTags1 array. Please keep in mind the amount of arguments in the "addToLookupTable" function call can vary from 1-4  key values. All the keys, in the "addToLookupTable" function call,  regardless of amount, must match in order to be added the the sTags1 array.

*** EXAMPLES***
_dtmPixelMapping("fund now", "approved", "product A", "5.00") pushes  "value1"  & "value2" to sTags1 array  -- Reason:  line with value1 has all the values & line with value2 ("fund now", "", "product A") has all of its values (2 in this case) matching.
 
_dtmPixelMapping("fund now", "review", "product C", "25.00") pushes  "value7"  & "value10" to sTags1 array  -- Reason line with value7  has all its values & line with value10  has all its values (only 1 in this case)  matching ("product C")


var sTags1 = [
    '//mj.test.com/1',
    '//mj.test.com/2',
    '//mj.test.com/3'
]

function _dtmInsertUpdatedPixels(decision, currOffers) {
    var fundingType = 

Open in new window

0
hi am having this error
doc
0
I need to run a php file in the background by clicking a input type button
without navigating away from the page that the button is placed

The php file have the following headers (basically it will prompt a file generated download)
I have no information to post.

I also would like to know in the php file which prompts the download of the file, if I can save a copy of the file on the server at the same time? how would I do this ?
	// output headers so that the file is downloaded rather than displayed
	header('Content-type: text/csv');
	header('Content-Disposition: attachment; filename="demo.csv"');

	// do not cache the file
	header('Pragma: no-cache');
	header('Expires: 0');

Open in new window

0
0
module cannot be found but i do have it
module
0
Hi Experts

Could you point why this HTML textarea is not actualized when changing the pictures since JS scripts shows it has changed?

Accordingly to:

 img002
What occurs is:
img003
Page Code:
  <div class="modal fade" id="mMidiaEditar" tabindex="-1" role="dialog" aria-labelledby="mMidiaEditarLabel">
    <div class="modal-dialog modal-lg" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="mMidiaEditarLabel">Mídia</h4>
        </div>
        <div class="modal-body">
          {{ csrf_field() }}
          <input type='hidden' id='id'/>
          <div class='form-group'>
            <label for='tituloEditar'>Título:</label>
            <input type='text' class='form-control' id='tituloEditar' name='tituloEditar'/>
          </div>

<!--  --->
          <div class='form-group'>
            <label for='descricaoEditar'>Descrição X:</label>
            <textarea class='form-control' id='descricaoEditar' name='descricaoEditar' rows="5"></textarea>
          </div>
<!--  --->

          <div class='form-group'>
            <label for='tipoparticipanteEditar'>Perfil:</label>
            <select id='tipoparticipanteEditar' name='tipoparticipanteEditar' class='form-control'>
              <option value='0'>Para todos os 

Open in new window

0
I'm trying to follow/understand some react concepts and I have a class component that has another class component and I'm having some trouble figuring out a bug with my setState. I'm including the two components below as well as the error I'm getting. In short, I don't know/understand what property is undefined.

MY HOME COMPONENT
import React from 'react';
import Login from '../../containers/Login/Login';


class Home extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      confirmationNumber: { text: '', isValid: true, error: '' },
    }
  }

  handleInputChange(event) {

    this.setState({
        [event.target.name]: {
            text: event.target.value,
            isValid: false,
            error: 'an error message'
        }
    });
  }

  render (){
    return (
      <div>
        {/* <p>You clicked {count} times</p> */}
        <button>
          Click me
        </button>
          <Login handleInputChange={this.handleInputChange}/>
      </div>
      );
  }
}

export default Home;

Open in new window


MY LOGIN COMPONENT
import React, { useState, useEffect } from 'react';
import './Login.css';
import CstmTextBox from '../../components/CstmTextBox/CstmTextBox';

class Login extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            focused: false,
            clickedLink: false
        }
    }

    handleSignIn(event) {
        alert("test");
    };

render (){
    return (
        <div className="LoginMainDiv">
            <CstmTextBox prompt="User Name: "/>
            <CstmTextBox prompt="Password: "/>
            <button onClick={this.handleSignIn}>Sign In</button>
            <input 
                type="text" 
                name="confirmationNumber" 
                onChange={this.props.handleInputChange}/>
        </div>
        );
    }
}

export default Login;

Open in new window

0
I m sending an ajax call in below method after return the success message i want to clear the form in same page so form also get cleared and success
 message also print in jsp page please help me out on this thanx a ton in advance.
 
 
 
 $(document).ready(function() {
	$("#data").click(function(evt) {
		evt.preventDefault();
		 if(save()){
			$.ajax({
				url: "Test.jsp",
				type: "post",
				data: {
				pS:$('#pS').val(),
				pType:$('#pType').val(),
				pCode:$('#pCode').val(),
				mYear:$('#mYear').val(),
				pDate:$('#pdate').val(),
				ppDate:$('#ppdate').val(),
				bDate:$('#bdate').val()},
				success: function(responseFromServer) {
	            	$.each(responseFromServer, function(resultMessageKey,resultMessageValue) {	
	                    $('#content').html(resultMessageKey);
	                });
	             },
	            error: function() {
	                alert(" Ajax call Failed to Update Values into Database");
	            }
			});
		 }
		 else
			 {
			 
			 }
	});
});

Open in new window

0
Hey there,  I have a PHP session cookie on our site which sets when a visitor comes to our site from a paid ad, and follows them through the site, and passes the variable to our CRM when they fill out a form.

See the PHP code below. Works!

function set_ad_cookies() {
	
	$vars = array('wordpress_sourcetagji');
	foreach ($vars as $k) {
		if (isset($_GET[$k]) && !isset($_COOKIE[$k])) {
			setcookie($k, $_GET[$k], 0, '/', $domains['cookie_domain']);
		}
	}
	
	  if (!isset($_COOKIE['wordpress_sourcetagji'])) {
		setcookie('wordpress_sourcetagji', $_GET['wordpress_sourcetagji'], 0, '/', $domains['cookie_domain']);
	  }
  }
  add_action('init', 'set_ad_cookies');

Open in new window


We are now finding that caching is stripping the cookie value when they navigate to a different page. Flywheel have said that this will happen as it's php and need to keep the caching on, and the only solution is to create the cookie in JS.

I've got very basic js skills, so how could i convert the above PHP code into JS so that   Scenario :
User1 comes into the site from an ad  https://mysite.com/?wordpress_sourcetagji=this-monster-cookie
User 1 visits varous pages on our site, and then fills out a form.
Cookie is still active and keeps it's value until the session ends.
0
I have a function that toggles a sub-menu when the parent is clicked.  This works fine.  However, if I click on another menu choice (parent) the sub-menu toggles open but the prior sub-menu that was toggled open stays open.  What I want is for each toggled sub-men closes if another parent is clicked so only one sub-menu is open at a time.

$("#menu-mobile .sub-menu").hide();
   
$('#menu-mobile').children().click(function(){
    $(this).children('.sub-menu').slideToggle('slow'); 
});

Open in new window

0
Hi Experts

Could you point a eay to present a photo by giving its url location by using PHP/ Laravel?

Accordingly with

<div class="box-noticias">
	<a href="javascript:void(0);" onclick='....;' >
	{{$vitrine->url}}
	</a>                    
</div>

Open in new window


Actually the{{$vitrine->url}}  presents the url itself, something like:

https://xxxxx.blob.core.windows.net/xxx/vitrines/87w91898.BMP

So I need to render it to show as a image.

Thanks in advance.
0
Hi All

I want to be able to amend the link in this div but do not have access to the code, only the JS file, can someone advise the most basic JS code to amend this to simply "https://www.abc.co.uk/" please

 <div id="toplogo">
      <a title="Link to homepage" href="https://www.abc.co.uk/test/example">#</a>
</div>
0
I'm new to creating/using APIs and React, so can someone give me some pros and cons (or links to articles that detail the pros and cons) of making your api calls directly in your react app vs. creating a separate api application?
0
Hi Experts

Could you point why a Controller method code is subtly returning to a jquery ajax without running and returning OK to JS ?

Accordingly to:

Vitrine.prototype.salvar = function(){
    
  console.log ('JS salvar');
  
  $.ajax({
    url: '/vitrine/salvar',
    
    method: "POST",
    data: {
      _token: $('input[name="_token"]').val(),
      id: $('#id').val(),
      url: $('#url').val(),
      inicio: $('#inicio').val(),
      termino: $('#termino').val(),
      title: $('#title').val(),
      description: $('#description').val(),
      points: $('#points').val()
    },
    error:function(data){
      hotsite.openModalCustom("Erro", data.responseText, "Entendi", "error");
    },
    success: function(data){
      hotsite.openModalCustom("Sucesso ao salvar", data.retorno, "Entendi", "success");
      hotsite.closeModal('mEditor');
      //hotsite.vitrine.filtrar();
    }
  });
};

Open in new window


and Controller method:


 public function salvar(Request $request){
   
	 //Forcing an error
	 //aaa;
	
	
	// Otherwise subtly exit with no traces.
	info('xxx');
   
	dd('aaa');

	$id=$request->input('id');
	$url=$request->input('url');
	$inicio=$request->input('inicio');
	$termino=$request->input('termino');

	$titulo = $request->input('title');
	$descricao = $request->input('description');
	$pontuacao = $request->input('points');

	try{
		if($id != '' &&  $id > 0){
		  $vitrine = Vitrine::find($id);
		}

		if(empty($vitrine)){
		  $vitrine = new Vitrine();
		  $vitrine->created_at=new \DateTime();
		}
			
		$vitrine->title = $titulo;
		$vitrine->description = $descricao;
		$vitrine->points = CustomFuncs::brancoParaNulo($pontuacao);
		$vitrine->url = $url;
		$vitrine->validity_start = empty($inicio) ? null : CustomFuncs::formatarDataUS($inicio);
		$vitrine->validity_end = empty($inicio) ? null : CustomFuncs::formatarDataUS($termino);
		$vitrine->updated_at=new \DateTime();
		
		info($vitrine);
		
		
		$vitrine->save();

	} catch (\Exception $e) {
		return response()->json(new Resultado(true,'','Erro ao salvar o vídeo'), 400);
	}

	return response()->json(new Resultado(false,'','Vídeo cadastrado com sucesso'));

}

Open in new window



The forced error:

img015
Thanks in advance!
0
Below js code, everything is working except

document.getElementById("row_" + eventid).style.display = 'none';

When it <a></a> is clicked, I hope to delete or invisible on the selected <div></div>
Do you know what goes wrong?


 function AddQty(eventid,qty,price) {
        var qty_value = document.getElementById(qty).value;
        var price_value = document.getElementById(price).value;
        var eventid_value = document.getElementById(eventid).value;
        
        document.getElementById("qty").value = parseInt(document.getElementById("qty").value) + parseInt(qty_value);
        document.getElementById("totalamount").value = parseFloat(document.getElementById("totalamount").value) + parseFloat(price_value);

        document.getElementById("shoppingcart").innerHTML = document.getElementById("shoppingcart").innerHTML +
       "<div id='row_' " + eventid_value  + " class='col-fs-12'>" +
            eventid_value + " " + qty_value + " " + price_value + " " + "<a style='cursor: pointer;' onclick='Remove(" + eventid_value + ")'>x</a>";
        "</div>";
    }
    function Remove(eventid) {        
        alert('Hi ' + eventid);
        document.getElementById("row_" + eventid).style.display = 'none';
    }

Open in new window

0
Hi,

I have one file which is written in traditional javascript. Trying to convert the file to ES6 class. Sending both the files. I am getting error on calling the function in the constructor.

Please check.

Error:
 Error: TypeError: mechanics.Debug.apply is not a function
baseClass.txt
TraditionalJS.txt
ES6Format.txt
0
Here's the code that I'm working on:

async auth(email, password) {
   1) const isDev = (process.env.ENV == 'local' || process.env.ENV == 'dev');
	//console.log(email);
    2) let match = {
      email: email,
      active: true
    };

    try {
        3) let user = await this.loadUser(match);        
      // validate the password hash
      if (!isDev) {
        await this.checkPasswordHash(password, user.password);
      }

      return this.success(user);
    } catch (err) {
      console.log('Error: ', err);
      return this.error(err);
    }
  }

Open in new window


Here are my questions / explanations. Could you please either "proof" or answer my quandaries?

1 I've not seen this before: const isDev = (process.env.ENV == 'local' || process.env.ENV == 'dev');

I'm assuming it's something similar to a ternary IF statement, but what does it mean? And I'm just shooting from my hip as far as it being a ternary IF statement. Generally, when faced with this kind of thing, I'll refer to https://davidwalsh.name/php-ternary-examples, but this genuinely baffles me.

2 "match" is a variable that houses an array consisting of two key / value pairs: "email" and "active." "email" is one of the arguments being passed into the method, so that's going to be coming from the login page.

3 loadUser looks like this:

  loadUser(match={}) {
    return new Promise( async (resolve, reject) => {
      this.model.aggregate([
        {$match: match},
       

Open in new window

0
Hi Experts


Could you clear why this Controller method isn't called as expected?

Accordingly with a previous question this form have 02 phases

1st: Upload a picture to a defined path - In my tests by using  
use Illuminate\Support\Facades\Storage;

Open in new window

It's perfectly locally uploaded.


2nd  The image url and details must to be saved at the table Vitrines

So, this method is called

Vitrine.prototype.salvar = function(){
    
  console.log ('JS salvar');  // Pass here
  
  $.ajax({
    url: '/admin/vitrine/salvar',
    method: "POST",
    data: {
      _token: $('input[name="_token"]').val(),
      id: $('#id').val(),
      url: $('#url').val(),
      inicio: $('#inicio').val(),
      termino: $('#termino').val(),
      title: $('#title').val(),
      description: $('#description').val(),
      points: $('#points').val()
    },
    error:function(data){
      hotsite.openModalCustom("Erro", data.responseText, "Entendi", "error");
    },
    success: function(data){
      hotsite.openModalCustom("Sucesso ao salvar", data.retorno, "Entendi", "success");
      hotsite.closeModal('mEditor');
      //hotsite.vitrine.filtrar();
    }
  });
};

Open in new window


img008
This method is configured at routes

Route::post('/admin/vitrine/salvar',['uses'=>'admin\VitrineController@salvar'])->middleware('cadastro');

Open in new window


But it doesn't seen it's called at VitrineController

 public function salvar(Request $request){
 
       

Open in new window

0
This works:

<script>

$(document).ready(function() {
	
	const fetchData = () => {
	  const promise = new Promise((resolve, reject) => {
		setTimeout(() => {
		  resolve("Loose Cannon Fitness");
		}, 100);
	  });
	  return promise;
	};
	
	
	setTimeout( async () => {
	  console.log("Smith and Gone");
	  var text = await fetchData();
	  console.log(text);
	}, 200);


});

</script>

Open in new window


What I'm attempting to do is get a better understanding of Callbacks, Promises and Async / Await(s).

To do that, I started with a very basic example and just built on that - adding / editing things in order to match what represented the new paradigm.

Here's the basic Callback:

$(document).ready(function() {
	
	x = function(cb) {
		setTimeout(function() {
			console.log("Smith and Gone");
			cb();
		}, 200);
	}

	y = function() {
		console.log("Loose Cannon Fitness");
	}
	
	x(y);
	
});

Open in new window


Here's the same result structured using ES6:

$(document).ready(function() {
	
	x = (cb) => {
		setTimeout(function() {
			console.log("Smith and Gone");
			cb();
		}, 200);
	}

	let y = () => {
		console.log("Loose Cannon Fitness");
	}
	
	x(y);
	
});

Open in new window


Here it is written using Promises:

const fetchData = () => {
  const promise = new Promise((resolve, reject) => {
	setTimeout(() => {
	  resolve("Loose Cannon Fitness");
	}, 100);
  });
  return promise;
};

setTimeout(() => {
  console.log("Smith and Gone");
  fetchData()
  .then(text => {
	console.log(text);
  });
}, 200);

Open in new window


And here it is written using an Async / Await dynamic:

$(document).ready(function() {
	
	const fetchData = () => {
	  const promise = new Promise((resolve, reject) => {
		setTimeout(() => {
		  resolve("Loose Cannon Fitness");
		}, 100);
	  });
	  return promise;
	};
	
	setTimeout( async () => {
	  console.log("Smith and Gone");
	  var text = await fetchData();
	  console.log(text);
	}, 200);

});

Open in new window


Just for the sake of drill, I did this:

$(document).ready(function() {
		
	const fetchData = () => {
		setTimeout(function() {
			console.log("Loose Cannon Fitness");
		}, 200);
	}

       setTimeout( async () => {
       console.log("Smith and Gone");
       var text = await fetchData();
       console.log(text);
      }, 200);
 
});

Open in new window


What I wanted to do was make "fetchData" a regular ES6 function as opposed to something that was incorporating a Promise.

The result was an error that looked like this:

Smith and Gone
stunt.php:54 undefined
stunt.php:25 Loose Cannon Fitness


Line #54 was "console.log(text)."

I'm assuming that "undefined" is a result of the fact that "await" is expecting a Promise.

Is that correct?

That said, is there a way to do what I've got written above where my "setTimeout" function works as it "awaits" fetchData written as an anonymous funtion?

This isn't something I would use in a practical setting. Rather, it's something I'm putting together for my own edification

What do you think?

In an effort to figure it out for myself, I tried this:

	const fetchData = () => {
		setTimeout(function() {
			//console.log("Loose Cannon Fitness");
			//var text = "Loose Cannon Fitness";
			//return text;
			return "Loose Cannon Fitness";
		}, 200);
	}

Open in new window


That didn't work.

I tried this:


Open in new window

0

JavaScript

123K

Solutions

42K

Contributors

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and  in almost every mainstream web browser.