如何正确链接异步函数?

时间:2015-11-19 20:04:54

标签: javascript node.js asynchronous typescript babeljs

我在ES7中使用异步功能,使用TypeScript,webpack和babel。主要的库和框架是expresssequelize

关键配置是:

.babelrc:

{
    "stage": 0,
    "optional": "runtime"
}

webpack.config.js:

{test: /\.ts$/, loader: 'babel-loader!ts-loader', exclude: /node_modules/},

tsconfig.json:

{
    "compilerOptions": {
        "noImplicitAny": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "target": "es6",
        "sourceMap": true,
        "experimentalDecorators": true,
        "experimentalAsyncFunctions": true
    },
    "files": [
    ]
}

我正在使用async

async function getCommentsOfVideoById(videoId: string): any {
    let commentData;
    ServiceLogger.info(`[VideoService]: fetching comment data.`);
    commentData = await VideoComment.findAll({
        where: {
            vid: videoId
        }
    });
    return commentData;
}

并将其命名为:

asyncRouter.get('/test/async/vservice', async(req, res) => {
    const videoService = new VideoService();
    ServiceLogger.info(`[VideServiceTest]: fetching comment data.`);
    let data111;
    try{
        data111 = await getCommentsOfVideoById('48');
    } catch (e) {
    } finally {
        console.log('No error');
        console.log(data111);
    }
    res.send(data111);
});

但是返回和发送的内容只是[ [Function] ],我不太明白。 <{1}}中的getCommentsOfVideoById内的日志永远不会输出。

令我困惑的是,类似的用法实际上是有效的。例如,我使用[VideoService]: fetching comment data.http函数编写了一个包装器:

bluebird

使用链接调用异步函数进行测试:

function httpGetAsync(options) {
    return new bluebird.Promise(function (resolve, reject) {
        console.info(`downloading from ${options}`);
        http
            .get(options, (res) => {
                let data = '';
                res.on('data', function (chunk: string) {
                    console.info('==========================');
                    console.info(chunk);
                    console.info('==========================');
                    data += chunk;
                });
                res.on('end', function () {
                    resolve(data);
                });
            })
            .on('error', reject);
    });
}

它按预期工作(当您访问async function a(url: string) { console.log('[a]: start'); let result; try { result = await httpGetAsync(url); //result = await divide(2, 3); //await Promise.delay(1000); } catch (e) { console.log('[a]: Exception', e); } finally { console.log('[a]: result', result); } console.log('[a]: end'); return result; } ``` ``` asyncRouter.get('/test/async/nesting', async(req, res) => { console.log('[/test/async/nesting]'); const url = req.query.url ? req.query.url : 'http://google.com/'; let response; try { response = await a(url); } catch (e) { console.log('[/test/async/nesting]: Exception', e); } finally { console.log('[/test/async/nesting]: response', response); } res.send(response); }); 时,您将被重定向)。

奇怪的是,http://domain/test/async/nesting?url=somewhat和我的代码都使用了sequelize,它应该(并且证明是)与bluebird兼容。查看awaitfindAll的类型定义,它们都具有相同的类型签名:

Promise

所以这个问题似乎并不存在。但实际问题是什么?

1 个答案:

答案 0 :(得分:0)

问题似乎是import * from bluebird as Promise与ES6原生Promise的名称冲突。当我将导入重命名为bluebird时,所有内容都按预期工作。