【问题标题】:koa js async await not working when used with ajax and promise与ajax和promise一起使用时,koa js async await不起作用
【发布时间】:2017-09-09 10:11:57
【问题描述】:

我使用 koa 作为 rest 后端,但是当使用 axios 调用 URL 时,我无法让路由和请求/响应正常工作。

server.js

const route = require('koa-route');
const serve = require('koa-static');
const Koa = require('koa');
const app = new Koa();
const path = require('path');
const bodyParser = require('koa-bodyparser');
const Datastore = require('nedb'),
      db = new Datastore({
          filename: __dirname +'/storage.db' ,
          autoload: true
      });
// something 
app.use(bodyParser());

app.use(serve(__dirname + '/dist'));

app.use(route.get('/api/projects', async function (next) {
    let projects = [];
    await db.find({}, function (err, docs) {
        projects = docs;
    });

    this.body = projects;
}));

const PORT = process.argv[2] || process.env.PORT || 3000;
app.listen(3000);

当我使用 axios 向 /api/projects 发出请求时,我得到一个空数组

来自我的 package.json

"scripts": {
    "start": "nodemon server.js --exec babel-node --presets es2015,stage-2"
  },

【问题讨论】:

    标签: koa


    【解决方案1】:

    您将 promise 与回调混合在一起,这很可能会导致您的问题。

    坚持使用承诺:

    app.use(route.get('/api/projects', async function (next) {
      let projects = await db.find({});
      this.body = projects;
    }));
    

    【讨论】:

    • nedb 不退出支持该结构,我已经更新了代码,但现在我得到 Uncaught (in promise) TypeError: this.props.project.map is not a function as an error跨度>
    • 如果它不支持承诺,你不能(直接)使用await。你需要像 nedb-promise 这样的东西来用 Promise 包装 NeDB 方法。
    猜你喜欢
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2018-11-21
    • 2021-06-05
    相关资源
    最近更新 更多