请考虑以下以串行/顺序方式读取文件数组的代码.readFiles返回一个promise,只有在按顺序读取所有文件后才会解析.
var readFile = function(file) {
... // Returns a promise.
};
var readFiles = function(files) {
return new Promise((resolve, reject) =>
var readSequential = function(index) {
if (index >= files.length) {
resolve();
} else {
readFile(files[index]).then(function() {
readSequential(index + 1);
}).catch(reject);
}
};
readSequential(0); // Start!
});
};
Run Code Online (Sandbox Code Playgroud)
上面的代码可以工作,但我不喜欢按顺序进行递归递归.是否有一种更简单的方法可以重写此代码,以便我不必使用我的奇怪readSequential功能?
最初我试图使用Promise.all,但这导致所有readFile调用同时发生,这不是我想要的:
var readFiles = function(files) {
return Promise.all(files.map(function(file) {
return readFile(file);
}));
};
Run Code Online (Sandbox Code Playgroud) 我正在尝试优化将数据插入MySQL的代码的一部分.我应该链接INSERT来制作一个巨大的多行INSERT还是更快的多个单独的INSERT?
所以我最近一直在玩knex,但是我发现自己处于一种我不知道该怎么办的情况.
所以我有这个问题:
knex.raw("INSERT INTO tablename (`col1`, `col2`, `col3`) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE col2 = VALUES(`col2`)",
[
['val1', 'hello', 'world'],
['val2', 'ohayo', 'minasan'],
]);
Run Code Online (Sandbox Code Playgroud)
由于某些原因,它给我一个错误Expected 2 bindings, saw 3.
我试过去做:
knex.raw("INSERT INTO tablename (`col1`, `col2`, `col3`) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE col2 = VALUES(`col2`)",
['val1', 'hello', 'world'],
['val2', 'ohayo', 'minasan'],
);
Run Code Online (Sandbox Code Playgroud)
这次没有错误,但它只插入第一个数组.
我也尝试将值设为对象:
[
{col1: 'val1', col2: 'hello', col3: 'world'},
{col1: 'val2', col2: 'ohayo', col3: 'minasan'},
]
Run Code Online (Sandbox Code Playgroud)
但仍然没有运气.
mysql ×2
benchmarking ×1
insert ×1
javascript ×1
knex.js ×1
node.js ×1
promise ×1
q ×1
sequential ×1