Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi -

Thought I understood somewhat how javascript promises work but guess I dont. I am trying to access the data the my request return. When I check the network I can clearly see the request has been made and data is in the response. But my simple console.log has no data?

JavaScript
function getData(){
  return new Promise(function(resolve, reject){
   window.api.getTimesByCompanyAndLocation(1, 5, function(error, data, response){
    if(error){
     reject({error, response});
    }
    else{
     resolve(response);
    }
   }
 }
}


What I have tried:


JavaScript
 getData().then((res) => {
  console.log(res);
})
Posted
Updated 11-Jun-20 15:17pm

1 solution

I have assembled a working example for you in the following fiddle

promise example - JSFiddle - Code Playground[^]

Markup:
HTML
<input type="text" placeholder="your favourite color?" />

<button type="button" onclick="getData()">
  Call Promise
</button>

<span id='PromiseStatus' />


JS/JQuery:
JavaScript
var $promiseStatus = $('#PromiseStatus');

function generateMessage(color) {
  return 'your favourite color is ' + color;
}

function getData() {
  $promiseStatus.text('Please wait...');
  var colorPromise = new Promise(function(resolve, reject) {
    var message = generateMessage($('input[type="text"]').val());

    // simulate call to api
    setTimeout(function() {
      resolve(message);
    }, 2000);
  });

  colorPromise.then(
    // the following function gets passed into the promise 'resolve' fn
    // callback. response param can be any object, e.g. api result data
    function(response) {
      console.log(response);
      $promiseStatus.text(response);
    });
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900