Search code examples
javascriptasynchronouspromisees6-promise

Async Function to determine the value of a property in a JavaScript object


I need to set a property of 'myObject' whose value will resolve after 2500 milliseconds. So I am making use of the Promise feature.

  const promise = new Promise(function(resolve,reject) {
        setTimeout(function(){
            resolve("Success!");
          }, 2500);
    });

    var myObject = {
        status : promise.then(function(success) {
            return success;
        })
    };

    console.log(myObject.status);

when I run this I am getting in NodeJS.

Promise { <pending> }

All the examples I am finding in the internet shows how to call a callback method. None of them tells how to assign a value of a property from an Async call. I very much would like to solve this myself. It will be very helpful to just point me to a correct example.


Solution

  • Are you trying to set the value of status after the promise resolves? If so don't see status to the value of the promise, set the value of status in the promise's callback:

    var myObject = {
        status: 'not set'
    };
    
    promise.then(() => {
       myObject.status = 'set';
       console.log(myObject.status);
    });
    

    Also if you console.log the value of status outside of the callback it will display the value at the time the promise was called, not the value at the time the promise resolved. That's why in the example above I put the call inside the callback.