简体   繁体   中英

node js async/await request in function

Hi I've some trouble with async/await in nodejs. I would use this into my factory in this way

//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;

So I call create into my test and I'm expecting that return will be execute after login, but flow isn't this!!!

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();
        });

    });

Test return me OK but in console I see Promise { <pending> } not real response after login process. Where is my error? Is correct working in this way?

Try this

//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;

AND

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

main();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM