javascript - 如何使用异步等待
问题描述
我需要在函数中运行各个步骤,但必须按特定顺序运行步骤。我尝试实现如下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
, 2在1之前登录。换句话说,空列表被传递给我的图形,因为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();
}
解决方案
你可以写一个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();
推荐阅读
- kubernetes - Fluentd td-agent 源插件的动态标记
- function - 增加值的函数如何工作?
- spring-boot - SpringMVC 用 post 改变 JSP
- java - 无法解析 ViewModelProviders 中 android.support.v4.app.FragmentActivity 的方法
- javascript - 即使我只有一个参数,我也会收到“包装承诺不可迭代错误”
- r - 如何将列表中的数据框添加在一起但仅用于匹配日期
- java - 编码 - 将 US-ASCII 转换为 UTF-8?
- php - PHP mail() 函数返回 false,但电子邮件已成功接收
- kotlin - 从注释中获取值失败
- java - 我的问题是关于从代码中删除“”时的错误