[英]nodejs async.whilst will only invoke once
如問題所述,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);
}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.