将客户端上的图像作为Base64上传到我想要的服务器
that()
上的下一个函数的结果,如果它是真的,则更新数据库并返回结果以下代码是我的实施链,但这似乎不正确,因为我无法从第一个链获得savePhotoOnDisk
的结果
savePhotoOnDisk(filenameWithPath)
.then(updateUserPhoto(result, userId, filename))
.then(FUNCTION(GET RESULT)
.then(OTHER FUNCTION() {
PRINT RESULT
});
或这个链:
savePhotoOnDisk(filenameWithPath)
.then(function(result){
updateUserPhoto(result, userId, filename);
})
.then(function (result) {
OTHER FUNCTION
})
.then(function (result) {
PRINT RESULT
})
.catch(function (v) {
log.info('error chaining');
});
function updateUserPhoto(result, userId, filename) {
log.info(result);
return new Promise(function (resolve, reject) {
var query = "UPDATE users SET userPhoto = ? WHERE userId = ? ;";
connection.query(query, [filename, userId], function (err, results) {
if (err) return reject(false);
if (results.length === 0) return reject(false);
resolve(true);
});
});
}
function savePhotoOnDisk(filename) {
return new Promise(function (resolve, reject) {
require("fs").writeFile(filename, base64Data, 'base64', function (err) {
log.info(err + "upload");
if (err == null)
resolve(true);
else
reject(false);
});
});
}
我是新手使用此nodejs功能,请帮助解决这个问题,谢谢
更新
savePhotoOnDisk(filenameWithPath)
.then(function (result) {
return {success:result};
})
.then(updateUserPhoto(success, userId, filename),function (result) {
console.log(result);
})
.catch(function (v) {
log.info('error chaining');
});
答案 0 :(得分:0)
你在承诺内部承诺这是问题。尝试将代码更改为类似的内容。
savePhotoOnDisk(filenameWithPath)
.then(function () {
return {
userId : userId,
fileName : fileName
}
})
.then(updateUserPhoto)
.then(FUNCTION(GET RESULT)
.then(OTHER FUNCTION() {
PRINT RESULT
});
function updateUserPhoto(data) {
var userId = data.userId;
var fileName = data.fileName;
// call your function as it was earlier.
}
修改强>
savePhotoOnDisk(filenameWithPath)
.then(updateUserPhoto.bind(true, userId, filename))
.then(function (result) {
OTHER FUNCTION
})
.then(function (result) {
PRINT RESULT
})
.catch(function (v) {
log.info('error chaining');
});
function updateUserPhoto(result, userId, filename) {
log.info(result);
return new Promise(function (resolve, reject) {
var query = "UPDATE users SET userPhoto = ? WHERE userId = ? ;";
connection.query(query, [filename, userId], function (err, results) {
if (err) return reject(false);
if (results.length === 0) return reject(false);
resolve(true);
});
});
}
function savePhotoOnDisk(filename) {
return new Promise(function (resolve, reject) {
require("fs").writeFile(filename, base64Data, 'base64', function (err) {
log.info(err + "upload");
if (err == null)
resolve(true);
else
reject(false);
});
});
}
答案 1 :(得分:0)
问题已解决
这是我创建简单链的正确代码,并将结果作为Promise
我希望对这篇文章有所帮助
savePhotoOnDisk(filenameWithPath, photoBase64).then(function (result) {
return updateUserPhoto(result, userId, filename);
}).then(function (save) {
if (save)
socket.emit('uploadUserPhoto', true);
else
socket.emit('uploadUserPhoto', false);
}).catch(function (v) {
socket.emit('uploadUserPhoto', false);
});