javascript - Knex await 如何执行数据库查询?
问题描述
我试图了解await
关键字在 KNEX 中的使用方式。举个例子:
knex.schema.createTable( ... );
这将返回this
这是 SchemaBuilder 的一个实例。它不会在数据库中执行创建表查询。但是,如果我坚持并await
在它面前。
await knex.schema.createTable( ... );
这现在将在数据库中执行创建查询。
我的理解是,await
它用于等待承诺解决,但在这种情况下,感觉就像发生了其他事情,因为不await
使用函数不会返回承诺。
这是如何运作的?
解决方案
如果您想知道在构造前面knex
编写时如何只发出请求,那么在这里。await
在幕后,knex
使用 apattern
返回带有then
字段的对象。
const asyncFunction = (delay) => {
return new Promise((resolve) => {
setTimeout(() => {
return resolve(delay);
}, delay);
})
}
const builder = (delay) => {
return {
then: async (resolve) => {
const result = await asyncFunction(delay);
return resolve(result);
}
}
}
const main = async () => {
const array = [];
for(let i=0; i<10; i++) {
array.push(builder(i));
}
console.log('array', array);
console.log('array[0]', array[0]);
console.log('await array[0]', await array[0]);
console.log('Promise.all for array', await Promise.all(array));
}
main();
此执行的结果将是控制台的以下输出
array [
{ then: [AsyncFunction: then] },
{ then: [AsyncFunction: then] },
{ then: [AsyncFunction: then] },
{ then: [AsyncFunction: then] },
{ then: [AsyncFunction: then] },
{ then: [AsyncFunction: then] },
{ then: [AsyncFunction: then] },
{ then: [AsyncFunction: then] },
{ then: [AsyncFunction: then] },
{ then: [AsyncFunction: then] }
]
array[0] { then: [AsyncFunction: then] }
await array[0] 0
Promise.all for array [
0, 1, 2, 3, 4,
5, 6, 7, 8, 9
]
可以看到,在then
使用 await 关键字或其他等待方式之前,不会调用函数内部的代码Promise
。
推荐阅读
- python - 如何将 p 标签的内容拆分为 BeautifulSoup 中的列表?
- r - 在 R 中创建动画时,月份按字母顺序显示
- mdriven - Viewmodelhelper.createfromViewmodel 方法中的错误
- windows - 如何在外部 SSD 上安装 WSL2?
- python - 检查Bot和Member是否在同一个频道
- linux - 如何构建旧版本的 GCC 和 BINUTILS?
- javascript - 有没有办法在不创建第二个数组来存储唯一值的情况下删除 javascript 中的重复值?
- python - 在本地机器上查看正在运行的 python 脚本的变量值
- sql - 在 Oracle 中使用动态列进行透视
- android - 在这种情况下如何使用触摸监听器