正确使用async,在承诺中使用double then()? node8,需要真正的babel到es5吗?

时间:2017-10-31 14:23:39

标签: javascript node.js async-await es6-promise babel

更新:

关于控制台stringify的问题是重复的;所以我用异步将我的问题改为另一个,因为是sam ecode

我有一个异步函数,通过sequelize orm获取记录,为什么

我的问题是

const genericResolver = async ( table, action , values ) => {

    resultValues = {};
    let resultValues =   await models[table].findById(values.id).then( function (data) {
      console.log(' ************** data');
      console.log(data);
      return data;
    }).then( function (data2) {
       console.log(' ************** data 2');
       console.log(data2);
      }
    );
    console.log('------ resultValues');
    console.log(resultValues );
    process.exit(1);

for data and data2 I get:

    tour {
      dataValues: 
       { id: 'd61802ff-3eec-4a72-97ca-832f51b96bf0',
         name: 'Chipre 2018',
         price: '1400.00',
         createdAt: 2017-09-05T04:01:27.642Z,
         updatedAt: 2017-10-31T11:29:39.484Z },
      _previousDataValues: 
       { id: 'd61802ff-3eec-4a72-97ca-832f51b96bf0',
         name: 'Chipre 2018',
         price: '1400.00',
         createdAt: 2017-09-05T04:01:27.642Z,
         updatedAt: 2017-10-31T11:29:39.484Z },
      _changed: {},
      _modelOptions: 
       { timestamps: true,
         validate: {},
         freezeTableName: true,
         underscored: false,
         underscoredAll: false,
         paranoid: false,
         rejectOnEmpty: false,
         whereCollection: { id: 'd61802ff-3eec-4a72-97ca-832f51b96bf0' },
         schema: null,
         schemaDelimiter: '',
         defaultScope: {},
         scopes: [],
         hooks: {},
         indexes: [],
         name: { plural: 'tour', singular: 'tour' },
         omitNull: false,
         sequelize: 
          Sequelize {
            options: [Object],
            config: [Object],
            dialect: [Object],
            queryInterface: [Object],
            models: [Object],
            modelManager: [Object],
            connectionManager: [Object],
            importCache: {},
            test: [Object] },
         uniqueKeys: {} },
      _options: 
       { isNewRecord: false,
         _schema: null,
         _schemaDelimiter: '',
         raw: true,
         attributes: 
          [ 'id',
            'name',
            'price',
            'seatsmax',
            'createdAt',
            'updatedAt' ] },
      __eagerlyLoadedAssociations: [],
      isNewRecord: false }

但对于'resultValues'我得到:

undefined

我正在做异步吗?我正在使用node8所以理论上我不需要将所有内容转换为ES5?只是进口或出口?我怀疑babel正在创建ES6代码

这是我的package.json

{
  "name": "myproj",
  "version": "1.0.0",
  "description": "GraphQL server",
  "main": "server.js",
  "scripts": {
    "start": "nodemon ./server.js --exec babel-node -e js",
    "test": "eslint . --ext .js --ext .jsx --ignore-path .gitignore --cache"
  },
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "babel-cli": "^6.24.0",
    "babel-eslint": "^8.0.0",
    "babel-preset-es2015": "^6.24.0",
    "babel-preset-stage-0": "^6.22.0",
    "eslint": "^4.7.1",
    "eslint-plugin-react": "^7.3.0",
    "nodemon": "^1.11.0"
  },
  "dependencies": {
    "bcrypt-nodejs": "0.0.3",
    "body-parser": "^1.17.1",
    "cors": "^2.8.3",
    "dotenv": "^4.0.0",
    "express": "^4.15.2",
    "graphql": "^0.9.1",
    "graphql-server-express": "^0.6.0",
    "graphql-tools": "^0.10.1",
    "jsonwebtoken": "^7.2.1",
    "lodash": "^4.17.4",
    "passport": "^0.4.0",
    "passport-jwt": "^3.0.0",
    "pg": "^7.2.0",
    "sequelize": "",
    "validator": "^6.2.0"
  }
}

1 个答案:

答案 0 :(得分:2)

这是因为对象在JS中作为引用传递,因此当您执行console.log(o)时,您将在控制台中看到实际值(而不是在调用console.log时传递给它的值)。

使用JSON.stringify时,您正在记录字符串,它是按值传递的。所以基本上当你使用JSON时,你会在调用console.log时看到值。

修改

关于您的新问题,问题是您没有从第二个data2回调中返回then。使用async/await时,您根本不需要使用then

const data = await models[table].findById(values.id);

或者,如果您愿意,只需返回data2即可在resultValues中看到相同的结果:

let resultValues = await models[table].findById(values.id).then(data => {
    console.log(' ************** data');
    console.log(data);
    return data;
}).then(data2 => {
    console.log(' ************** data 2');
    console.log(data2);

    return data2; // <== return here
});

console.log('------ resultValues');
console.log(resultValues );