0

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.

Tiny Rick
  • 284
  • 3
  • 19
  • 1
    I'm a little unclear on what you're asking. Are you trying to set myObject.status to a value after the promise resolves? – Daniel Gimenez Jul 23 '18 at 12:50
  • @Daniel Yes. I have to set the value of 'status' attribute after the promise resolves. – Tiny Rick Jul 23 '18 at 12:52
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ASDFGerte Jul 23 '18 at 12:53
  • Please note that for this specific example, using `await` in an `async` context works: `(async () => console.log({ status: await promise }))();` expected output: "Object { status: 'Success!' }", after 2.5 seconds - if `promise` is newly created and not already resolved. – ASDFGerte Jul 23 '18 at 12:59

1 Answers1

2

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.

Daniel Gimenez
  • 18,530
  • 3
  • 50
  • 70