Can asynchrony in JavaScript save await?

Can asynchrony in JavaScript save await?

I knew before that to synchronously obtain the results of asynchronous execution in JavaScript , you must use await ; in the for loop, if you don’t use Promise.All, the asynchrony will not work. But every time you need to wait for the execution result, you need to use async and await . I think it is troublesome and not good-looking. It would be fine if you remember how to write these two words, but if you don't remember them, you will misspell them every time, which will interrupt your train of thought, and it will not look good if such words suddenly appear.

So I made a concerted effort to solve this problem. As a programmer who often takes pride in reinventing the wheel, I think it is my responsibility to make a small contribution to the change of JavaScript .

Consider the following code:

const trans = require('node-google-translate-skidz');

function translate (str, strEn, tarEn) {
  let p = () => {
    return new Promise((resolve, reject) => {
      trans({
        text: str,
        source: strEn ? strEn : 'zh',
        target: tarEn ? tarEn : 'en'
      }, function (result) {
        resolve(result.translation)
      });
    })
  }
  let an = async () => {
    let b = await p()
    console.log(b);
  }
  return an()
  //console.log(b)
}


let c = translate('中文')
console.log('c', c)

This code is probably the best solution I could come up with to solve the asynchronous problem, but the answer is still unsuccessful. But I finally understand why in JavaScript , no matter how you wrap it or what technology you use, you can't really avoid async and await .

Look at where the translate method is called and print the translation result after the call. The purpose of doing this is, of course, that I hope to print it after there is a result. If Promise { <pending> }, it means that it is executed directly without waiting.

In order to achieve the purpose of printing after the result is available, I cleverly encapsulated an async()=>{await}, in translate method, and then let translate return the result of await execution. But this method will not work, because the final printed result is still what I want to avoid at all costs

Why? Because I forgot that async only works on function , which means async has a scope. After I executed the method let c = translate('中文') , because I did not tell the compiler translate needed await (I thought that translate had implemented async and await , so translate would automatically wait for the execution result to return. However, due to the existence of scope, the scope inside translate cannot affect the execution of translate method.), the compiler directly executed console.log('c', c) , which printed Promise { <pending> }.

By introducing the concept of scope, async and await in the method body cannot make the method call level also async and await . You can probably understand why await cannot be omitted in asynchrony in JavaScript .

This concludes the article about Can await be omitted in JavaScript asynchrony? For more information about asynchrony in JavaScript, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JS Asynchronous Stack Tracing: Why await is better than Promise
  • How to implement asynchronous calls with async/await in JS
  • NodeJs handles asynchronous methods through async/await
  • async/await and promise (asynchronous operation problem in nodejs)

<<:  About the problem of vertical centering of img and span in div

>>:  Loading animation implemented with CSS3

Recommend

How to completely delete and uninstall MySQL in Windows 10

Preface This article introduces a tutorial on how...

JavaScript to achieve simple drag effect

This article shares the specific code of JavaScri...

Tips for optimizing MySQL SQL statements

When faced with a SQL statement that is not optim...

Summary of the use of element's form elements

There are many form elements. Here is a brief sum...

Login interface implemented by html+css3

Achieve results First use HTML to build a basic f...

Detailed explanation of Vite's new experience

What is Vite? (It’s a new toy on the front end) V...

Implementation of mysql configuration SSL certificate login

Table of contents Preface 1. MySQL enables SSL co...

How to use Docker-compose to deploy Django applications offline

Table of contents Install Docker-ce for the devel...

A Brief Analysis on the Time Carrying Problem of MySQL

The default time type (datetime and timestamp) in...

How to implement the webpage anti-copying function (with cracking method)

By right-clicking the source file, the following c...

How to safely shut down MySQL

When shutting down the MySQL server, various prob...

How to Learn Algorithmic Complexity with JavaScript

Table of contents Overview What is Big O notation...

Practice of using SuperMap in Vue

Table of contents Preface Related Materials Vue p...

Nginx+FastDFS to build an image server

Installation Environment Centos Environment Depen...