节点js async / await请求函数

时间:2017-05-01 13:41:13

标签: node.js asynchronous async-await

嗨,我在nodejs中遇到了async / await问题。我会以这种方式将它用于我的工厂

//foo.js    

   var rp = require('request-promise');

   function Foo(options) {
        this.options = options;
    }

    function create() {
        return new Foo(login());
    }

    async function login() {
        const options = {
            method: `POST`
            ,json: true
            ,uri: `http://xxxxxx/login`
            ,body: {username: 'abcd', password: '1234'}
        };
        try {
            const response = await rp(options);
            return Promise.resolve(response)
        }
        catch (error) {
            return Promise.reject(error);
        }
    }
  module.export.create = create;

所以我将create调用到我的测试中,我希望返回将在登录后执行,但是流量不是这个!!!

var Foo = require('foo');

describe('using my utils into project', function () {

        it('using real case', function (done) {

            var foo = Foo.create();
            console.log(foo.options);
            done();
        });

    });

测试返回我没问题但是在控制台中我看到Promise { <pending> }在登录过程后没有真正的响应。 我的错误在哪里?这样做是否正确?

1 个答案:

答案 0 :(得分:0)

试试这个

//foo.js    

var rp = require('request-promise');

function Foo(options) {
    this.options = options;
}

async function create() {
    var temp = await login()
    return Promise.resolve(new Foo(temp));
}

function login() {
    return new Promise(async(resolve, reject) => {
        const options = {
            method: `POST`
            ,json: true
            ,uri: `http://xxxxxx/login`
            ,body: {username: 'abcd', password: '1234'}
        };
        try {
            const response = await rp(options);
            return resolve(response)
        }
        catch (error) {
            return reject(error);
        }
    });
}
module.export.create = create;

async function main() {
    var foo = await Foo.create();
    console.log(foo.options);
}

main();