-1

Not sure why the script doesn't execute after .then

abc().then(function(result) {
  var fetch_os = localStorage.getItem('os');
  console.log(fetch_os);
});


function abc() {
  localStorage.setItem('os', 'linux');
  return;
}

UPDATE: I think maybe I haven't explained it well. Although was trying to keep it summarised and short. Here is the full code for this issue.

$(document).on('change', '#metamask-eth-paths', function(e) {
  $('.popup-loader-main-wallet').removeClass('hidden');
  $('body').css({
    'cursor': 'wait'
  });
  var path = $(this).val();
  if (path == '2') {
    var path_txt = "Account";
  } else {
    var path_txt = "Account";
  }
  var type = "eth";
  //Test function
  MetaMaskConnect().then(function(result) {
    var meta_address = localStorage.getItem('metamask_address');
    console.log(meta_address);
    if (meta_address !== null) {
      var address = meta_address
      $.ajax({
        url: '/wallet/get-metamask-hd-address/',
        type: 'GET',
        data: {
          type: type,
          address: address,
          add_path: path_txt
        },
        success: function(result) {
          $('body').css({
            'cursor': 'default'
          });
          $('.popup-loader-main-wallet').addClass('hidden');
          if (result) {
            $('#hd-section').empty();
            $('#hd-section').append(result.response_html);
            $("#hd-wallet-modal").modal('show');

          }
        },
        error: function(error) {
          return false
        }
      })
    } else {
      $('body').css({
        'cursor': 'default'
      });
      $('.popup-loader-main-wallet').addClass('hidden');
      $('#hd-section').empty();
      $('#hd-section').append('<h3>An error occured please try again later</h3');
    }
    console.log(meta_address);

  });
  return;

});

function MetaMaskConnect() {
  connectWindow = null
  if (connectWindow == null) {
    connectWindow = window.open("http://localhost:3300");
  } //
  window.addEventListener("message", (event) => {
    if (event.origin !== "http://0.0.0.0:8033") {
      console.log("1")
    }
    if (event.data == null) {
      console.log("2")
    }
    if (event.data !== null && event.origin == "http://0.0.0.0:8033") {
      console.log("3")
      window.removeEventListener("message", event, true);
      connectWindow.postMessage("address_request", "http://localhost:3300");
      window.addEventListener("message", (event) => {
        if (event.origin !== "http://0.0.0.0:8033")
          console.log("4")
        if (event.data == null) {
          console.log("5")
        } else {
          console.log("6")
          var address = event.data;
          console.log("Address: " + address)
          window.removeEventListener("message", event, true);
          //remove old localStorage param
          localStorage.removeItem('metamask_address');
          //add new localStorage param
          localStorage.setItem('metamask_address', address);
          //var result = true;
          return;
        }
      }, false);
    }
    return;
  }, false);
  return true;
}

UPDATE: I have added return Promise which made the code fully execute. return Promise.resolve("Success");

  • 3
    Aren't you getting an error? `abc()` doesn't return a promise. It returns `undefined`, which has no `then()` method. – Barmar Jun 05 '22 at 22:03
  • please check the full detailed code. – 2StepsFromHell Jun 05 '22 at 22:24
  • @2StepsFromHell Doesn't make a difference, the mistake is still the same. `MetaMaskConnect()` does not return a thing with a `.then()` method. – Bergi Jun 05 '22 at 22:32
  • @Bergi isnt MetaMaskConnect function returning this: return result, & result = true??. in python for instance if we want a function to return something we would do it that way :/. something like this? var result = true. return new Promise(result) ?? – 2StepsFromHell Jun 05 '22 at 23:21
  • No, that's returning from the `addEventListener` callback function. The only return statement in the `MetaMaskConnect` function itself is the `// return;`. – Bergi Jun 06 '22 at 00:00
  • @Bergi I have added `2 returns` for the `eventlisteners`, and added: `return true;` for the function itself. Still the code after `.then(function` wont run. No error is showing :S. Have updated the code up with that 3 return. – 2StepsFromHell Jun 06 '22 at 14:35

1 Answers1

1

Promises are a tool to manage asynchronous operations in a standard way.

When you have a promise you can call then() on it to pass a function that will be called after the promise has settled.

The code you have:

  • Doesn't include any promises
  • Doesn't include any asynchronous operations (so adding promises would add pointless complexity).

To run code after a synchronous function, just put it after the function call.

abc();
var fetch_os = localStorage.getItem('os');
console.log(fetch_os);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • please check the full detailed code. I tried this method earlier but it didn't work because JS would run .getItem without waiting for .setItem to happen first.. – 2StepsFromHell Jun 05 '22 at 22:23
  • Well, your extended code is now asynchronous … but `MetaMaskConnect` doesn't return a promise. So the reason it doesn't work is the same. The solution is that you need to make `MetaMaskConnect` return a promise that resolves when you want it to resolve. – Quentin Jun 05 '22 at 22:24
  • You have mentioned: "The solution is that you need to make MetaMaskConnect return a promise that resolves when you want it to resolve". But haven't given any solution applied on the code itself. If you can that would be great and can be considered as good answer. – 2StepsFromHell Jun 06 '22 at 14:43
  • @2StepsFromHell — You did move the goalposts on this question. See https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises however. – Quentin Jun 06 '22 at 14:44
  • I did check this page already yesterday it doesn't explain for a Newbie in JS. Looks more like advanced hence this is why I have asked here on Stackoverflow. Of course before posting I looked for an answer (for 2 days). You reckon I should open a new question instead of updating things here? – 2StepsFromHell Jun 06 '22 at 14:54
  • @2StepsFromHell — A new question is just going to get closed as a duplicate of that one (which has 28 different answers already). You should probably be thinking about tutorials (e.g. [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)) rather then looking for solutions to specific problems when you lack an understanding of the fundamentals. – Quentin Jun 06 '22 at 14:56
  • I am reading over the guide now. Its actually straight forward, guess just needed guidance on where to start with promises. I'm Newbie with JS ;). Cheers mate! – 2StepsFromHell Jun 07 '22 at 01:26