【问题标题】:ctx.body undefined in async/await functionctx.body 在 async/await 函数中未定义
【发布时间】:2018-05-24 09:10:30
【问题描述】:

我正在尝试使用 koa 从我的节点服务器返回 api 调用的结果到我的角度前端。这是我的控制器,它需要一个 npm 模块来提供对其 api 的访问。 Await 应该等待结果然后返回,我错了吗?我在以前的项目中做了类似的事情,但我从数据库中询问数据。 为什么它不起作用?

const color = require('colourlovers');

exports.getAllColors = async (ctx) => {
  ctx.res.body = await color.get('/color/FFFFFF', { format: 'json' }, (err, data) => {
    console.log(data);//<---here is logging the data
    return data;
  });
  console.log(ctx.res.body);//<---here is undefined
  ctx.status=200;
};

【问题讨论】:

    标签: node.js api server async-await koa


    【解决方案1】:

    你不能等待color.get,因为它使用回调而不是承诺(嗯,你可以等待它,但它并没有达到你的预期)。所以要使用await,你需要自己构建promise:

    ctx.res.body = await new Promise((resolve, reject) => {
        color.get('/color/FFFFFF', { format: 'json' }, (err, data) => {
            if(err) reject(err);
            else resolve(data);
        });
    });
    

    现在它将等待 promise 被解决或拒绝。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 2021-02-17
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      相关资源
      最近更新 更多