Getting value from a returned promise from an asynchronous function

I'm used to the proposed aync / await syntax and there is some kind of unintuitive behavior. Inside the "async" function, I can console.log the correct line. However, when I try to return this string, it returns a promise instead.

Check this entry: does async / await implicitly return a promise? , it’s pretty clear that any “asynchronous function ()” will return a promise, not a value. It's great. But how do you get access to value? If the only answer is a “callback”, that’s fine, but I was hoping there might be something more elegant.

// src // ========================================== require("babel-polyfill"); var bcrypt = require('bcrypt'); var saltAndHash = function(password){ var hash; return new Promise(function(resolve, reject){ bcrypt.genSalt(10, function(err, salt) { bcrypt.hash(password, salt, function(err, hash) { resolve(hash); }); }); }) } var makeHash = async function(password){ var hash = await saltAndHash(password); console.log("inside makeHash", hash); return(hash); } // from test suite // ========================================== describe('Bcrypt Hashing', function(){ it('should generate a hash', function(){ var hash = makeHash('password'); console.log("inside test: ", hash); should.exist(hash); }) }) // output to console: // ========================================== inside test: Promise { _d: { p: [Circular], c: [], a: undefined, s: 0, d: false, v: undefined, h: false, n: false } } inside MakeHash $2a$10$oUVFL1geSONpzdTCoW.25uaI/LCnFqeOTqshAaAxSHV5i0ubcHfV6 // etc // ========================================== // .babelrc { "presets": ["es2015", "stage-0", "react"] } 
+5
source share
1 answer

Yes, you can only access it with a callback:

 makeHash('password').then(hash => console.log(hash)); 

Or, of course, you can simply make another asynchronous function that waits for it:

 it('should generate a hash', async function(){ var hash = await makeHash('password'); console.log("inside test: ", hash); should.exist(hash); }) 

It is not possible to access the result of the promise synchronously.

+9
source

Source: https://habr.com/ru/post/1242766/


All Articles