Is it possible to rewrite the following Promise code with async/await?

Asked 1 years ago, Updated 1 years ago, 77 views

Thank you for your help.
As stated in the title, is it possible to rewrite the code shown below to do the same with async/await?

function hello(){
    return new Promise ((resolve, reject) = > {
        setTimeout(()=>{
            resolve('hello');
        },2000);
    });
}

hello().then(result)=>{
    console.log(result);
});

I looked it up myself and concluded that I probably couldn't do it, but I also thought, "Maybe I can do it...?", so I asked you a question.
This may be a rudimentary question, but I would appreciate it if you could let me know.

javascript node.js promise

2022-09-30 19:30

2 Answers

As you think, async/await cannot rewrite this.

In particular, for hello functions, if you create a Promise in new Promise to convert asynchronous processing by the callback function to Promise, you cannot rewrite it to an async function.I think we have no choice but to write the hello function like this.

For the latter part of the program, then must be used to wait for the results of hello() because wait cannot be used anywhere other than in the async function.

However, in the future, top-level wait will be introduced into JavaScript, which will allow you to rewrite the latter part as follows:

const result=wait hello();
console.log(result);

Top-level wait is a feature that allows you to write await on top-level modules in addition to "in the async function".The top level of a module is the outermost part of the JavaScript file, which is a module, which is not one of the other functions.


2022-09-30 19:30

Once surrounded by async.

I think it is impossible to suddenly use wait at the top level at the moment, as Mr. Fairy wrote.

async encloses the following example:

function hello(){
  return new Promise ((resolve, reject) = > {
      setTimeout(()=>{
          resolve('hello');
      },2000);
  });
}

async function hoge() {
  result=await hello()
  console.log(result)
}

hoge()

If you want to use an unknown function, you can write the following:

function hello(){
  return new Promise ((resolve, reject) = > {
      setTimeout(()=>{
          resolve('hello');
      },2000);
  });
}

(async function(){
  result=await hello()
  console.log(result)
})();

For your reference, see
I think this document is almost the same source as your question.

async function-JavaScript|MDN

Quote

function resolveAfter2Seconds(){
  return new Promise(resolve=>{
    setTimeout(()=>{
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall(){
  console.log('calling');
  const result = wait resolveAfter2Seconds();
  console.log(result);
  // expected output: 'resolved'
}

asyncCall();


2022-09-30 19:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.