gpt4 book ai didi

javascript - nodejs async.whilst 只会调用一次

转载 作者:行者123 更新时间:2023-12-03 05:19:55 25 4
gpt4 key购买 nike

正如问题所述,async.whilst 只会调用一次。但是,如果我传递一个包含 2 个对象(长度为 2)的数组,它只会调用一次——而不是为数组的每个索引调用一次。

//if previous awsKeys detected in req.body / images are detected : delete them.
exports.multipleDelete = function (req, res, next) {
var body = req.body;
//if object already has existing keys, they will be in the body.existingKeys array.
var awsKeyTrash = body.existingKeys;
if (awsKeyTrash !== undefined) {
var j = 0;
async.whilst(
function () {
return j < awsKeyTrash.length;
},
function () {
var picInfo = awsKeyTrash[j];
s3.deleteObject({
Bucket: aws.bucket,
Key: picInfo.key
}, function (err, data) {
if (err) {
console.log('delete err', err);
//if there is an error, set pic information to original
req.body[picInfo.name] = picInfo.picUrl;
req.body[picInfo.key] = picInfo.awsKeyVal;
j++;
};
console.log('deleted')
console.log('j ', j)
j++;
res.send('deleted');
});
},
function (err) {
console.log('profile edit , pic delteion err : ', err);
return res.status(409).send({
message: ['Unable to edit profile at this time. Try again']
});
})
next();
}
else {
next();
}
}

这是 body.existingKeys 数组的示例:

     Array[
{
awsKeyVal: "users/66085aa8-6501-4f90-973c-1b18edf4087eScreenShot2016-12-05at10.03.07PM.png",
key: "awsPictureKey",
name: "picture",
picUrl: "https://example-bucket.s3.amazonaws.com/users/66085aa8-6501-4f90-973c-1b18edf4087eScreenShot2016-12-05at10.03.07PM.png"
},
{
awsKeyVal: "coverphoto/7180d1ae-748c-4b96-86cb-5cb29cebdc9bScreenShot2016-12-10at3.13.18PM.png",
key: "awsCoverKey",
name: "cover",
picUrl: "https://example-bucket.s3.amazonaws.com/coverphoto/7180d1ae-748c-4b96-86cb-5cb29cebdc9bScreenShot2016-12-10at3.13.18PM.png"
}]

最佳答案

async.whylist接受您未调用的回调。

看起来您的 next() 也放错了地方。

此外,最后一个函数不是错误处理程序。它只是将错误作为第一个参数,如果没有错误,则该参数可能为 null。

async.whilst(
function () {
return j < awsKeyTrash.length;
},
function ( callback ) {
var picInfo = awsKeyTrash[j];
s3.deleteObject({
Bucket: aws.bucket,
Key: picInfo.key
}, function (err, data) {
if (err) {
console.log('delete err', err);
//if there is an error, set pic information to original
req.body[picInfo.name] = picInfo.picUrl;
req.body[picInfo.key] = picInfo.awsKeyVal;
j++;
};
console.log('deleted')
console.log('j ', j)
j++;
res.send('deleted');

callback();
});
},
function (err) {

if( err ) {
console.log('profile edit , pic delteion err : ', err);
return res.status(409).send({
message: ['Unable to edit profile at this time. Try again']
});
}

// If someone else handles errors, pass it on here. Otherwise,
// throw or something else to block program flow
next(err);
}
);

关于javascript - nodejs async.whilst 只会调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41435376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com