我怎样才能在javascript中重构我的异步代码(我正在使用Promise)

时间:2017-09-13 03:10:08

标签: node.js asynchronous es6-promise

dbConnect(res).then((conn)=>{
query(conn,res,
  `SELECT * FROM programs WHERE user_id = ?`,
  [
    user_id
  ]
).then((programList)=>{

  new Promise((resolved,rejected)=>{
    for(let i = 0; i<programList.length;i++){
      query(conn,res,`
        SELECT * FROM open_programs WHERE program_id = ?`,[programList[i].program_id])
      .then((opList)=>{
        Object.assign(programList[i],{openList : opList});
        console.log(programList[i]);
        if(i == (programList.length-1)){
          resolved(programList)
        }
      })
    }
  }).then((result)=>{
    conn.release();
    res.json(toRes(SUCCESS,
      { data : result }
    ));
  })
});
});

'dbConnect','query'是我的自定义方法,由'Promise'

组成

在这段代码中,首先我得到firstResults(schema = programs) 在我使用'for循环'中的firstResults.program_id获取nextsqlResults之后 和对象分配firstresult和nextResults

分配后,我会回复组合数据

我如何开发此代码?

2 个答案:

答案 0 :(得分:1)

Promise.allArray.map会在这里为您提供帮助。未测试的:

dbConnect(res).then(conn => {
    return query(conn, res, `SELECT * FROM programs WHERE user_id = ?`, [
        user_id,
    ]);
}).then(programList => {
    return Promise.all(programList.map( program => 
        query(
            conn,
            res,
            `SELECT * FROM open_programs WHERE program_id = ?`,
            [program.program_id],
        ).then(opList => {
            console.log(program);
            return Object.assign(program, { openList: opList });
        });
}).then(result => {
    conn.release();
    res.json(toRes(SUCCESS, { data: result }));
});

您应该验证result是您在此代码后寻找的数据结构。

使用babel-plugin-transform-object-rest-spread插件清理了一点:

dbConnect(res).then(conn =>
    query(conn, res, `SELECT * FROM programs WHERE user_id = ?`, [
        user_id,
    ])
).then(programList =>
    Promise.all(programList.map(program => 
        query(
            conn,
            res,
            `SELECT * FROM open_programs WHERE program_id = ?`,
            [program.program_id],
        ).then(opList => ({
            ...program,
            openList: opList
        })
    ))
).then(result => {
    conn.release();
    res.json(toRes(SUCCESS, { data: result }));
});

答案 1 :(得分:0)