Condivisione della tecnologia

Spiegazione dettagliata della funzione asincrona ES6 (10)

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Cosa sono le funzioni asincrone? In una parola, è lo zucchero sintattico della funzione Generator.

const gen = function* () {
  const f1 = yield readFile('/etc/fstab');
  const f2 = yield readFile('/etc/shells');
  console.log(f1.toString());
  console.log(f2.toString());
};

const asyncReadFile = async function () {
  const f1 = await readFile('/etc/fstab');
  const f2 = await readFile('/etc/shells');
  console.log(f1.toString());
  console.log(f2.toString());
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

La funzione asincrona consiste nel sostituire l'asterisco (*) della funzione Generator con async e sostituire yield con wait, e il gioco è fatto.

I miglioramenti della funzione asincrona alla funzione Generatore si riflettono nei seguenti quattro punti:

(1) Attuatore integrato.
L'esecuzione della funzione Generator deve fare affidamento sull'esecutore, quindi c'è il modulo co e la funzione async viene fornita con il proprio esecutore. In altre parole, l'esecuzione delle funzioni asincrone è esattamente la stessa delle funzioni ordinarie, con una sola riga.

Modulo co: Il modulo co è un piccolo strumento rilasciato dal famoso programmatore TJ Holowaychuk nel giugno 2013, utilizzato per l'esecuzione automatica delle funzioni del generatore.
Il modulo co ti evita di scrivere l'esecutore della funzione Generator.

// Generator 函数
var gen = function* () {
  var f1 = yield readFile('/etc/fstab');
  var f2 = yield readFile('/etc/shells');
  console.log(f1.toString());
  console.log(f2.toString());
};

//co模块使用
var co = require('co');
co(gen); //co 函数返回一个 Promise 对象
co(gen).then(function (){
  console.log('Generator 函数执行完成');
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

(2) Migliore semantica.
Async e wait hanno una semantica più chiara di asterisco e yield. async significa che è presente un'operazione asincrona nella funzione e wait significa che l'espressione seguente deve attendere il risultato.
(3) Applicabilità più ampia.
Secondo la convenzione del co modulo, il comando yield può essere seguito solo da una funzione Thunk o da un oggetto Promise, mentre il comando wait della funzione async può essere seguito da un oggetto Promise e da un valore di tipo primitivo (valore numerico, stringa e booleano valore, ma verrà automaticamente convertito nell'oggetto Promise risolto immediatamente).
(4) Il valore restituito è Promessa.
Il valore restituito della funzione asincrona è un oggetto Promise, il che è molto più conveniente rispetto al valore restituito della funzione Generator che è un oggetto Iterator. È possibile utilizzare il metodo then per specificare l'azione successiva.

Inoltre, la funzione async può essere considerata come più operazioni asincrone, racchiuse in un oggetto Promise, e il comando wait è lo zucchero sintattico del comando then interno.

1. Funzioni asincrone di base

// 定义一个异步函数
async function fetchData() {
    return 'Data fetched';
}

// 调用异步函数
fetchData().then(data => {
    console.log(data); // 输出: Data fetched
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

2. Usa wait per attendere Promise

// 模拟一个异步请求函数
function getUserData() {
    return new Promise(resolve => {
        setTimeout(() => resolve({ name: 'Alice' }), 1000);
    });
}

// 异步函数使用 await 等待 Promise
async function printUserData() {
    try {
        const userData = await getUserData();
        console.log(userData); // 输出: { name: 'Alice' }
    } catch (error) {
        console.error(error);
    }
}

printUserData();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

3. Gestione degli errori

// 异步函数中的错误处理
async function riskyFunction() {
    try {
        const result = await Promise.reject('An error occurred');
    } catch (error) {
        console.error(error); // 输出: An error occurred
    }
}

riskyFunction();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

4. Funzioni asincrone concatenate

async function asyncOperation() {
    return 'Operation completed';
}

async function chainAsyncFunctions() {
    try {
        const result1 = await asyncOperation();
        const result2 = await asyncOperation();
        console.log(result1, result2); // 输出: Operation completed Operation completed
    } catch (error) {
        console.error(error);
    }
}

chainAsyncFunctions();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

5. funzione asincrona come funzione di gestione degli eventi

// 假设有一个按钮元素
const button = document.querySelector('#myButton');

// 为按钮添加点击事件处理函数
button.addEventListener('click', async event => {
    try {
        const data = await fetchData();
        console.log(data);
    } catch (error) {
        console.error(error);
    }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

6. funzione asincrona e Promise.all

// 异步函数返回多个 Promise
async function fetchUsers() {
    return ["User1", "User2", "User3"];
}

async function fetchPosts() {
    return ["Post1", "Post2", "Post3"];
}

// 使用 Promise.all 并行处理多个异步操作
async function fetchAllData() {
    try {
        const [users, posts] = await Promise.all([fetchUsers(), fetchPosts()]);
        console.log(users, posts); // 输出: [ 'User1', 'User2', 'User3' ] [ 'Post1', 'Post2', 'Post3' ]
    } catch (error) {
        console.error(error);
    }
}

fetchAllData();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20