I am using async and await for achieving this. Following is my code and it is working as expected.
function publish() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("SUCCESS");
}, 3000);
});
}
var res;
async function sendRequest() {
console.log("START\n");
res = await publish();
console.log("RESULT: ",res)
console.log("END\n");
}
sendRequest();
Following is the output:
START
SUCCESS
END
But what I am trying to achieve is given below:
function publish() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("SUCCESS");
}, 3000);
});
}
var res;
async function sendRequest() {
console.log("START\n");
res = await publish();
console.log("RESULT: ",res)
console.log("END\n");
return res;
}
/**
* EXPECTED BEHAVIOUR
* Assume this function is an action of a controller class
* It will call sendRequest() and waits for its response.
* Once received, it will return that response to the client who called the action.
*/
function controller () {
return sendRequest();
}
/**
* ACTUAL BEHAVIOUR: It will out put following
* START
* FINAL RESPONSE Promise { <pending> }
* RESULT: SUCCESS
* SEND
*/
var endResult = controller ();
console.log("FINAL RESPONSE",endResult);
So my question is why this FINAL RESPONSE Promise { <pending> }
is printed before RESULT: SUCCESS
.
- If this is the behaviour of
async
await
, how can I achieve my expected behaviour. I don't want to usethen()
in my controller. - Is it possible using while loop? May be I am wrong. It would be great if any one can guide me.