Await & Async function

Hello ,
I want to write a programme which comprises of 2 function func1 and func2 , I want it in such a way that function 1 should wait for 3 seconds for user to input any value. Within 3 second if input is given then it should be displayed and func2 executes after that . And if no input is given within 3 seconds then func2 executes directly. It is sort of required to use async and await . Below is the source code which I tried

const prompt  = require('prompt-sync')();
 function firstMessage(){
  var d ;
    //timeout function for delaying request
    setTimeout( async function(){
     d=  await inpp();     
    }, 3000);

 function secondMessage() {

 async function inpp()
  var z = prompt("Enter value to pass");
  return z ; 

However , this function is printing value of d & 2 and then asking for value . Can anyone please tell me where am I wrong and help me modify the code.

Thank You

This sounds like homework…

The first thing to remember is that async/await work on Promises. So, anything on which you want to await should return or be wrapped in a Promise. Have you read up on Promises?

So, you have two things that you want to happen. Those will need to be in the same Promise. Is there a way to just wait until the first one finishes? [hint, hint]

Not actually homework , but I am self-learning Javascript. So it’s like I am myself deciding to make few pgms to implement what I have learnt.
I have not learnt with promises before , I thought that maybe I will be able to do it.

async/await is built on Promises - they basically are Promises, but wrapped in syntax that is easier to read. You can’t really understand them without having at least a basic understanding of Promises.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.