0

Code below is returning a Promise Object in form of Promise{object}. I am unable to get it in actual object

var msg_bo = new msgBO();
   var msg = JSON.parse(req.body.message);
   var cnf; 


   uploadFile()

   function upload(){
      return new Promise((resolve,reject)=>{
         cnf = msg_bo.uploadMessageAttachments(msg, req.file);
         resolve()
      })
   }

   async function uploadFile(){
         await upload()
         console.log('my response ',cnf)
         res.send({status:'success',message: {
            text:msg,filename:cnf
         }})

   }
4

2 回答 2

0

将您的代码更改为此(假设您的顶级函数可以await):

const msg_bo = new msgBO();
const msg = JSON.parse( req.body.message );

await uploadFile();

function upload(){
    return new Promise( ( resolve, reject ) => {
        const cnf = msg_bo.uploadMessageAttachments( msg, req.file );
        resolve( cnf );
    } );
}

async function uploadFile() {

    const cnf = await upload();
    console.log( 'my response ', cnf );
    res.send( {
        status: 'success',
        message: {
            text: msg,
            filename: cnf
        }
    } );
}

以上可以简化为:

const msg_bo = new msgBO();
const msg = JSON.parse( req.body.message );

const cnf = await upload();

console.log( 'my response ', cnf );

res.send( {
    status: 'success',
    message: {
        text: msg,
        filename: cnf
    }
} );

function upload(){
    return new Promise( ( resolve, reject ) => {
        const cnf = msg_bo.uploadMessageAttachments( msg, req.file );
        resolve( cnf );
    } );
}

...虽然您实际上并没有使用任何真正的asyncAPI,但您可以同步完成所有操作(假设uploadMessageAttachments不返回 a Promise<T>):

const msg_bo = new msgBO();
const msg = JSON.parse( req.body.message );

const cnf = msg_bo.uploadMessageAttachments( msg, req.file );

console.log( 'my response ', cnf );

res.send( {
    status: 'success',
    message: {
        text: msg,
        filename: cnf
    }
} );
于 2020-02-11T04:55:22.313 回答
0

这应该工作,

   var msg_bo = new msgBO();
   var msg = JSON.parse(req.body.message);
   var cnf; 


   uploadFile()

   function upload(){
      return new Promise((resolve,reject)=>{
         const cnf = msg_bo.uploadMessageAttachments(msg, req.file);
         resolve(cnf);
      })
   }

   async function uploadFile(){
         const cnf = await upload();
         console.log('my response ',cnf);
         res.send({status:'success',message: {
            text:msg,filename:cnf
         }})

   }
于 2020-02-11T09:57:04.113 回答