简体   繁体   English

如何正确使用异步等待?

[英]How to use async await correctly?

Im using nodejs to do the backend data transmission and reading the uploading file information from the angular front end website.我使用nodejs做后端数据传输并从angular前端网站读取上传文件信息。

I want to put the query result to the json object.我想把查询结果放到json object。

I expect my output json object would as the same as results object.我希望我的 output json object 将与结果相同 ZA8CFDE6331BD59EB2AC96F8911C4B666 But the variable remain undefined.但变量仍未定义。

output: output:

json---> undefined
results---> {
  app_name: 'QuickVPN',
  app_package_name: 'com.lipisoft.quickvpn',
  app_version: '1.16',
  isDuplicate: '[{"cnt":0}]'
}

app.controller.js app.controller.js

    const appModel = require('../models/app.model');
    exports.createApp = async(req, res, next) => {
      try {
        const json = await appModel.uploadAppPreview(req);
        console.log('json--->', json);
        res.status(200).json(json);
      } catch (err) {
        if (!err.statusCode) {
          err.statusCode = 500;
        }
        next(err);
      }
    }

app.module.js app.module.js

const db = require('../util/db');
module.exports = class appModel {
  static uploadAppPreview(req){

    let app_name = '';
    let app_package_name = '';
    let app_version = '';
    let r = '';
    const formidable = require('formidable');
    var form = new formidable.IncomingForm();
    let final_json = new Object();

    form.parse(req, function (err, fields, files) {
      const fs = require('fs');
      const os_type = fields.os_type;
      const user_id = fields.user_id;

      const dir = `./app/${os_type}/previews/`;

      fs.mkdirSync(dir, { recursive: true });

      const oldpath = files.my_file.filepath;
      // const newpath = dir + files.my_file.originalFilename;

      const exec = require('child_process').exec;
      var getApkInfo = function(callback){
        exec(`aapt dump badging "${oldpath}"`,
          async (error, stdout, stderr) => {
            const output = stdout.split("'");
            let app_label_index = stdout.split("application-label:");
            app_name = app_label_index[1].split("'")[1];
            app_package_name = output[1];
            app_version = output[5];
            let json = new Object();
            json.app_name = app_name;
            json.app_package_name = app_package_name;
            json.app_version = app_version;

            const sql = `
              SELECT
                count(*) as cnt
              FROM
                APP_LIST_TABLE
              WHERE
                os_type = ? and app_package_name = ? and app_version = ? and user_id = ?
            `;
            const a =  await db.query(sql, [os_type, app_package_name, app_version, user_id]);
            json.isDuplicate = JSON.stringify(a[0]);
            callback(json);
        })
      };

      return getApkInfo(
        function(results) {
          final_json = results;
          console.log('results--->',results);
          return results;
        }
      )
    });
  }
}

updated app.module.js(added return promise) but the json variable is still undefined.更新了 app.module.js(添加了返回承诺),但 json 变量仍未定义。

  static uploadAppPreview(req){

    let app_name = '';
    let app_package_name = '';
    let app_version = '';
    let r = '';
    const formidable = require('formidable');
    var form = new formidable.IncomingForm();
    let final_json = new Object();

    form.parse(req, function (err, fields, files) {
      const fs = require('fs');
      const os_type = fields.os_type;
      const user_id = fields.user_id;

      const dir = `./app/${os_type}/previews/`;

      fs.mkdirSync(dir, { recursive: true });

      const oldpath = files.my_file.filepath;
      // const newpath = dir + files.my_file.originalFilename;

      const exec = require('child_process').exec;
      var getApkInfo = function(callback){
        exec(`aapt dump badging "${oldpath}"`,
          async (error, stdout, stderr) => {
            const output = stdout.split("'");
            let app_label_index = stdout.split("application-label:");
            app_name = app_label_index[1].split("'")[1];
            app_package_name = output[1];
            app_version = output[5];
            let json = new Object();
            json.app_name = app_name;
            json.app_package_name = app_package_name;
            json.app_version = app_version;

            const sql = `
              SELECT
                count(*) as cnt
              FROM
                APP_LIST_TABLE
              WHERE
                os_type = ? and app_package_name = ? and app_version = ? and user_id = ?
            `;
            const a =  await db.query(sql, [os_type, app_package_name, app_version, user_id]);
            json.isDuplicate = JSON.stringify(a[0]);
            callback(json);
        })
      };


      return new Promise(function(resolve, reject) {
        final_json = getApkInfo(
          function(results) {
            console.log('results--->',results);
            return results;
          }
        )
        return resolve(final_json);
      })

    });

  }

you have to wrap ur logic inside Promise你必须将你的逻辑包装在 Promise

module.exports = class appModel {
    static uploadAppPreview(req) {
        return new Promise((resolve, reject) => {
//here will be your logic
            if (error) {
                return reject(error)
            }
            return resolve(results) // on success
        })
    }
}

await only works if u r calling a promise function it will not work on call back functions只有当你 r 调用 promise function 时才有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM