首页 > 解决方案 > 如何使用异步等待

问题描述

我需要在函数中运行各个步骤,但必须按特定顺序运行步骤。我尝试实现如下Async功能:

async function test() {
    await setTimeout(function() { console.log('1'); }, 5000);
    await setTimeout(function() { console.log('2'); }, 2000);
    console.log('3');
}
test();

控制台中的预期结果应该是 1, 2, 3 但我得到 3, 2, 1。似乎该await参数被忽略了。

编辑setTimeout函数在上面的说明性示例中仅用于模拟繁重的任务。在我的项目中,我不会使用它。实际上,我需要连接到数据库,然后重新格式化结果,然后再进行下一步。即使包含async-await, 21之前登录。换句话说,空列表被传递给我的图形,因为async-await没有考虑到。这是我当前的代码:

async function refreshData() {
    myLabel = [];
    myValues = [];
    myJSON = [];
    const sqlite3 = require('sqlite3').verbose();
    let db = new sqlite3.Database(fullPath + '/annex/data.db');

    await new Promise(resolve => {
        db.each('SELECT firstName, age FROM Info;', function(err, row) {
            console.log('1');
            myLabel.push(row.firstName);
            myValues.push(row.age);
            myJSON.push(JSON.stringify(row));
        });
        resolve(myValues);
        resolve(myLabel);
        resolve(myJSON);        
    });

    console.log('2');
    db.close();
    popChart(myLabel, myValues);
    popTable(); 
}

标签: javascriptasync-await

解决方案


你可以写一个wait函数:

const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

async function test() {
  console.log('1');
  await wait(5000);
  console.log('2');
  await wait(2000);
  console.log('3');
}
test();

推荐阅读