-2

Javascript code, trying to resolve a promise immediately:

           var promiseData;

            var promise = <<<promise maker>>>.then(function (myContent) {
                console.log("success");
            }, function () {
               console.log("fail!");   
            });

            Promise.resolve(promise)

            console.log("about to return");

            return promiseData;

which output's to the console:

about to return
success

I have a requirement to make the promise return immediately (the promise is being created in a callback method, and the method needs to return a value immediately, returning the data later means we are no longer in the correct context and the value (that has not yet been returned) has already been used (as undefined).

Any suggestions of what I might be doing wrong?

Update: <<<promise maker>>> is a call to a dependency that returns a promise;

Ninjanoel
  • 2,864
  • 4
  • 33
  • 53
  • 3
    What is "promise maker"? What do you expect `Promise.resolve(promise)` to do? – Pointy Jan 30 '19 at 15:08
  • i have a dependency that is returning a promise, so I've left that bit out and labelled it <>. I expected Promise.resolve will resolve the promise? clearly i'm having trouble so just let me know where i'm going wrong please :-S – Ninjanoel Jan 30 '19 at 15:10
  • 1
    You should await the promise so that any code reliant on the result won't run until it's complete. – Tyler Roper Jan 30 '19 at 15:10
  • 2
    you can't return a value from an async operation immediately like the caller expects: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Daniel A. White Jan 30 '19 at 15:11
  • @Tyler i cant, i'm in a framework that needs the value immediately – Ninjanoel Jan 30 '19 at 15:12
  • `Promise.resolve()` is used to *create* a new Promise, one that is "pre-resolved". You can only resolve a promise from within its initialization callback function. – Pointy Jan 30 '19 at 15:13
  • 1
    @Nnoel Then you either need to find a way to avoid the "promise maker", or you need to change your framework (or figure out how to do async stuff in the framework) – Bergi Jan 30 '19 at 15:13
  • 2
    The primary use-case of promises is when a value *won't* be available immediately. – Tyler Roper Jan 30 '19 at 15:14
  • 1
    @Bergi obviously not an option in the real world to ask the client to choose an entirely new front end framework cause they need one extra feature – Ninjanoel Jan 30 '19 at 15:15
  • 1
    @Nnoel Then tell the client that the feature they're asking for isn't an option given their framework. The framework they're using does not offer immediate data. That said, if you were able to provide the broader scope of this framework and your specific concerns as it relates to an `await` or callback, then maybe that is a better question. We are slowly peeling back the layers of an [**XY Problem**](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Tyler Roper Jan 30 '19 at 15:19
  • @Nnoel With the given information, we can only tell you that what you are asking for is impossible. You might want to elaborate on the framework and the promise maker, we might be able to suggest a workaround. – Bergi Jan 30 '19 at 15:22
  • @Bergi... i have a promise... and I want to app to do nothing till the promise is resolved.. then continue execution. like postman arrives, hold him at the door till you ready, don't let him visit the next house until the job is done and the parcel can be handed to the postman. if you kick off the job when the postman arrives.. then let him leave then return with the parcel you need to give him... you cant chase him down the road at that point cause you not dressed for that! – Ninjanoel Jan 30 '19 at 15:30
  • @Nnoel That is exactly what I have suggested above: *awaiting* the result. You tell your code to stop, and not move a line further until the result is available. – Tyler Roper Jan 30 '19 at 15:31
  • @Nnoel You only told me *how* you want to solve this, not *why* or *what* promise you have this problem with. And I can only repeat that what you are describing is not possible - promises are asynchronous. – Bergi Jan 30 '19 at 15:33
  • @Tyler.... the syntax above is the upteenth version of the code.. i tried await async.. i tried loads of stuff, I dont know where the error is, but it may be the promise maker, it may be my code... but I dont know how to await properly, so please show me the code to do it. – Ninjanoel Jan 30 '19 at 15:34
  • 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) – tkausl Jan 30 '19 at 15:35
  • @Nnoel You cannot use `async`/`await` if the framework you are using doesn't support promises. The postman doesn't care how you do your task and dress up, he's gone when he's gone. – Bergi Jan 30 '19 at 15:36
  • @Bergi... i could use a while loop to hold him at the door, but i know how bad practice that would be so i'm not even going to attempt it. – Ninjanoel Jan 30 '19 at 15:37
  • @Nnoel No, you can't use a while loop, because while you are holding him at the door you cannot do your task or dress up. Please believe me that I mean "impossible" when I say it. – Bergi Jan 30 '19 at 15:38
  • @Bergi.. :-( well thanks for the help everyone. (i dont mean that as sarcastic as that sounds, lol) – Ninjanoel Jan 30 '19 at 15:41

2 Answers2

0

It looks like you expect Promise.resolve(promise) to immediately halt, wait until the promise is resolved, and continue afterwards. That would come close to synchronous execution.

However, Promise.resolve(value) returns a Promise that immediately resolves with value, it does not resolve an existing Promise.

What you're looking for is await (or just Promise.then):

var promise = <<<promise maker>>>.then(function (myContent) {
    console.log("success");
}, function () {
    console.log("fail!");   
});

promise.then(function() {
  console.log("about to return");
});

You might observe that I left out the promiseData in the snippet. That's because in order to return the data at the right moment, you have to be asynchronous there as well. So you have to actually return a Promise that will resolve with promiseData, it comes down to:

<<<promise maker>>>
  .then(function(promiseData) {
    console.log('success');
    return promiseData;
  })
  .then(function(promiseData) {
    console.log('about to return');
    return promiseData;
  })
  .catch(function(err) { console.log('fail!'); })
Dominik Schreiber
  • 2,629
  • 1
  • 23
  • 33
  • I suggested async/callback as well, but OP said that that's not an option - they need the value *immediately*. – Tyler Roper Jan 30 '19 at 15:20
  • @dominik... i got excited about your answer... but i'm unsure where the "return" in each "then" is goings, and then I see Tyler's comment and am thoroughly confused now :-( – Ninjanoel Jan 30 '19 at 15:26
  • @Tyler, by immediately i mean it needs to wait for the promise to resolve before continuing with the rest of the code. – Ninjanoel Jan 30 '19 at 15:27
0

If I am not wrong, this function flow is near what you need, but it also returns a promise resolved into promiseData:

async function getPromiseData() {
  try {
    const promiseData = await <<<promise maker>>>;
    console.log("success");
    console.log("about to return");
    return promiseData;
  } catch (err) {
    console.log("fail!");
  }
}
vsemozhebuty
  • 12,992
  • 1
  • 26
  • 26