当我使用此代码时,它只更新第一个值的数据库的一个值。它不适用于循环;只有一行受到影响。我想更新所有行。如何从表中选择列值并将其更新为循环中的其他列值?
asyncloop方法: -
function readData () {
return new Promise (function(resolve,rejection){
conn.connect().then(function () {
var request = new sql.Request(conn);
request.query('Select * FROM demo Order by id ;', function (err, data) {
if (err) { console.log(err) }
else {
try {
resolve(data)
conn.close();
}
catch (err) {
console.log(err);
}
}
});
});
});
}
function writedata() {
return new Promise(function (resolve, rejection) {
let count = 0
asyncLoop(temp, function (item, next){
asyncLoop(id,function(newitem,newnext){
conn.close();
conn.connect().then(function () {
var request = new sql.Request(conn);
console.log(item);
console.log(newitem);
request.input("language", sql.VarChar, item)
request.input("id", sql.SmallInt, newitem)
request.query('update demo set ru = @language where id = @id ;', function (err, data) {
if (err) {
console.log(err)
} else {
try {
count++
conn.close();
if (count == 4) {
resolve(data)
}
} catch (err) {
console.log(err);
}
next();
newnext();
}
});
});
});
});
});
}
readData().then(function (data) {
for (var i = 1; i < 5; i++) {
temp.push(data['recordset'][i]['EN']);
id.push(data['recordset'][i]['ID']);
}
writedata().then(function (data) {
console.log(data);
});
});
使用asyncloop更新了代码,但有一些循环问题
答案 0 :(得分:1)
尝试下面的代码,通知我任何错误。另外,根据需要修改计数值:
function writedata() {
return new Promise(function (resolve, rejection) {
let count = 0
for (i = 0; i < 5; i++) {
conn.close();
conn.connect().then(function () {
var request = new sql.Request(conn);
console.log(temp[i]);
console.log(id[i]);
request.input("language", sql.VarChar, temp[i])
request.input("id", sql.SmallInt, id[i])
request.query('update demo set ru = @language where id = @id ;', function (err, data) {
if (err) {
console.log(err)
} else {
try {
count++
conn.close();
if(count == 5)
resolve()
} catch (err) {
console.log(err);
}
}
});
});
}
});
}
答案 1 :(得分:1)
请尝试Asyncloop
,而不是for
循环下面是相同的语法。
asyncLoop(ARRAY, function(item, next) {
[Function/Operation block]
next();
}
});
}, function(error) {
[Error Handling Block]
});
答案 2 :(得分:0)
尝试下面的代码,我希望它有所帮助
// If this.notification has the multiple subscriptions
if(this.notifications && this.notifications.length >0)
{
this.notifications.forEach((s) => {
if(!s.closed)
s.unsubscribe();
});
}
// if this.subscription has direct object
if(this.subscription && !this.subscription.closed)
this.subscription.unsubscribe();
}