鍍金池/ 問答/HTML/ koaJS數(shù)據(jù)獲取正確但是不能返回給前端

koaJS數(shù)據(jù)獲取正確但是不能返回給前端

具體接口代碼如下。

修改了一下格式,求指教,循環(huán)為何只能取到第一次的數(shù)據(jù):

'use strict';
const organizationDb = '../../../models/organization';
const userOrganizationDb = '../../../models/user_organization';

module.exports = async function (ctx) {
    
    try {
        const res = await getDbData(ctx);
        ctx.json({
            status: 0,
            msg: '成功',
            res
        });
    } catch (error) {
        console.log(error);
        ctx.json({
            status: 1,
            msg: '失敗'
        });
    }
};

function getDbData(ctx){
    const db = ctx.app.db;
    const organizationModel = db.import(organizationDb);
    const userOrganizationModel = db.import(userOrganizationDb);
    let results = [];
    
    return new Promise((resolve, reject) => {
    
        organizationModel.findAll({
            where:{
                name: {
                    $like: 'ext-%'
                }
            }
        }).then(ori => {
            Array.from(ori).forEach(record => {
                userOrganizationModel.findAll({
                    where: {
                        'organization_id':record.id
                    }
                }).then(result => {
                    //只會(huì)返回第一次循環(huán)的內(nèi)容,后續(xù)的內(nèi)容push不到數(shù)組里,為什么,應(yīng)該在哪里resolve呢?
                    results.push(result);
                    resolve(results);
                })
            });
        });
    });

}
回答
編輯回答
毀憶

使用await的時(shí)候then和catch是無效的

'use strict';
const organizationDb = '../../../models/organization';
const userOrganizationDb = '../../../models/user_organization';

module.exports = async function (ctx) {
    // 引入數(shù)據(jù)庫(kù)依賴
    const db = ctx.app.db;
    const organizationModel = db.import(organizationDb);
    const userOrganizationModel = db.import(userOrganizationDb);
try{
    const data = await Promise1xxx;
    const data2 = await Promise2xxx(data);
    ctx.body = data2; 
    }
    catch(e) {
    ctx.body = {
        errmsg:e.message
    };
   }
};

你代碼問題太多了

  1. async/await promise混用
  2. forEach中使用了return,其實(shí)外面拿不到
  3. 沒有使用標(biāo)準(zhǔn)的try/catch去寫koa
2017年2月24日 04:38
編輯回答
憶當(dāng)年

建議學(xué)習(xí)一下 async 函數(shù)的正確用法~
await了,就不需要then
這個(gè)是教程

2018年8月8日 09:01
編輯回答
墨沫

用了await,不會(huì)有then回調(diào),另外兩位說的是對(duì)的,我搞錯(cuò)了

2018年7月2日 05:19