fileUpload.js
var Uploader = require('s3-image-uploader');
var express = require('express');
var config = require('./../config.js');
var Promise = require('promise');
var uploader = new Uploader({
aws: {
key: config.awsKey,
secret: config.awsSecret
},
websockets: false
});
exports.fileUpload = function(fileName) {
new Promise(function(resolve, reject) {
uploader.upload({
fileId: 'someUniqueIdentifier',
bucket: 'quflip',
source: './public/images/' + fileName,
name: fileName
},
function(data) { // success
console.log('upload success:', resolve);
resolve(data);
},
function(errMsg, errObject) { //error
reject(false);
});
});
};
logintest.js
var awsUpload = require('./../config/fileUpload.js');
var userData = function(req, res) {
console.log("true/false" + awsUpload.fileUpload(profile_image));
在这里发生的是,我在console.log中获得了未定义的值。因此,这意味着回调未传递数据。我怎样才能有效地传递数据以达到进一步的目的
最佳答案
如果您希望函数实际返回promise,则请更改以下内容:
exports.fileUpload = function (fileName) {
new Promise(function(resolve, reject) {
// ...
});
};
对此:
exports.fileUpload = function (fileName) {
return new Promise(function(resolve, reject) {
// ...
});
};
没有
return
语句,函数将不会返回您正在创建的承诺。但是即使那样,您也无法像这样使用它:
console.log("true/false" + awsUpload.fileUpload(profile_image));
您将必须使用以下内容:
awsUpload.fileUpload(profile_image).then(result => {
console.log("true/false" + result);
});
或者,如果您使用的是
async
/ await
并且在async
函数内部:console.log("true/false" + await awsUpload.fileUpload(profile_image));
关于node.js - promise在回调中给出未定义的结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43100313/