对象属性不变

时间:2019-04-25 12:57:04

标签: javascript

我有以下代码:

var olddata = req.body;
    var saveimage = '';
    if (req.files.headerImage) {
      var fileuploaded = req.files.headerImage;
      lib1n618.saveUploadedFile(fileuploaded, '/home/', '', false, function(err, filename) {
        saveimage = filename;
      });
    } else {
      saveimage = rows[0].datas.headerImage;
    }
    Object.assign(olddata, { headerImage: saveimage});

问题是,即使headerImage变量正确设置为新上传的图像url,olddata对象的值saveimage也不会更改。 我已经尝试过olddata.headerImage = saveimage,但也不起作用。

2 个答案:

答案 0 :(得分:0)

Bayesian callback ,并且在包含方法之后执行回调。

lib1n618.saveUploadedFileObject.assign(olddata, { headerImage: saveimage});回调中的saveimage = filename之前执行,因此olddata将永远不会设置为正确的值。

saveUploadedFile

答案 1 :(得分:0)

使用异步过程时,除非已使用await,否则无法在下一行获得结果。您应该以某种方式等待,直到可以使用它们为止。一种简单的解决方案是添加承诺。

var olddata = req.body;
new Promise(function (resolve, reject) {
    var saveimage = '';
    if (req.files.headerImage) {
        var fileuploaded = req.files.headerImage;
        // This is an async process
        lib1n618.saveUploadedFile(fileuploaded, '/home/', '', false, function (err, filename) {
            saveimage = filename;
            resolve(saveimage);
        });
    } else {
        // This is sync
        saveimage = rows[0].datas.headerImage;
        resolve(saveimage);
    }
}).then(function (saveimage) {
    // Now you have the data
    Object.assign(olddata, { headerImage: saveimage });
})