在javascript中实现回调

时间:2016-06-23 13:41:19

标签: javascript node.js promise chai-as-promised

我的助手js文件中有一个函数可以在S3上传文件:

if(images) {
  images.forEach(function(imageRecord) {
    awsHelper.uploadToAWS('assets', assetObject.id, imageRecord);
  });            
}

我的消费者功能是这样的:

if(images) {
  images.forEach(function(imageRecord) {
    awsHelper.uploadToAWS(
      'assets',
      assetObject.id,
      imageRecord,
      function (success, failure) {
        //handle success or failure
      });
  });
}

我想在这里介绍一个回调方法,这样我可以从我的帮助函数到我的调用函数获得成功和失败。怎么可以实施?     需要我的消费者功能如下所示,但辅助功能会是什么样的?

{{1}}

3 个答案:

答案 0 :(得分:2)

为什么不在你的" uploadToAWS"中添加一个Callback?喜欢:

module.exports.uploadToAWS = function uploadToAWS(folderName, fileName, fileData, callback){

然后进行简单的验证并在上传完成/失败时调用它(传递响应)

s3.putObject(data, function(err, data){
      if (err) { 
        console.log(err);
        console.log('Error uploading data: ', data); 
        if(typeof callback === 'function') callback(err , data);
      } else {
        console.log('succesfully uploaded the image!');
        if(typeof callback === 'function') callback(err , data);
      }
    });

在此之后,您将完全按照您的建议使用它

if(images){
            images.forEach(function(imageRecord){
                awsHelper.uploadToAWS('assets', assetObject.id, imageRecord, function (err , data) {
                    //handle success or failure    
                });
            });            
        }

答案 1 :(得分:1)

您需要将回调函数作为辅助函数的参数传递。

试试这个:

module.exports.uploadToAWS = function uploadToAWS(folderName, fileName, fileData, callback){

    var s3 = new AWS.S3({ params: {Bucket: ‘myBucket’} });

    var keyName = folderName + "/" + fileName;

    var buffer = new Buffer(fileData.replace(/^data:image\/\w+;base64,/, ""),'base64')

    var data = {
        Key: keyName, 
        Body: buffer,
        ContentEncoding: 'base64',
        ContentType: 'image/jpeg'
    };

    s3.putObject(data, function(err, data){
       if (err) { 
         callback(err);
       } else {
         callback(null, data);
       }
    });
}

答案 2 :(得分:1)

因此,通过改写Promise风格,您可以:

module.exports.uploadToAWSAsync = 
    function uploadToAWSAsync(folderName, fileName, fileData){
        return new Promise(function(resolve, reject){
            var s3 = new AWS.S3({ params: {Bucket: ‘myBucket’} });

            var keyName = folderName + "/" + fileName;

            var buffer = new Buffer(fileData.replace(/^data:image\/\w+;base64,/, ""),
                                    'base64')

            var data = {
                    Key: keyName, 
                    Body: buffer,
                    ContentEncoding: 'base64',
                    ContentType: 'image/jpeg'
                };

            s3.putObject(data, function(err, data){
                  if (err) { 
                    console.log(err);
                    console.log('Error uploading data: ', data); 
                    reject(err);
                  } else {
                    console.log('succesfully uploaded the image!');
                    resolve();
                  }
                });
        });
    }

您可以按如下方式重写消费者代码:

//fire them all off in one go
var promises = images.map(function(imageRecord){
    return awsHelper.uploadToAWSAsync('assets', assetObject.id, imageRecord);
}); 
Promise.all(promises).then(function(){
    //success, everything uploaded
}).catch(function(err){
    //something went wrong
});