Getting value from returned promise from async function

吃可爱长大的小学妹 提交于 2019-12-29 08:39:06

问题


I'm getting used to the proposed async/await syntax and there's some unintuitive behavior. Inside the "async" function, I can console.log the correct string. However, when I try to return that string, instead, it returns a promise.

Checking this entry: async/await implicitly returns promise? , it's pretty clear that any "async function()" will return a promise, NOT a value. That's fine. But how do you get access to the 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"] }

回答1:


Yes, you only can access it using a callback:

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

Or of course, you can just make another async 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);
})

There is no way to access the result of a promise synchronously.



来源:https://stackoverflow.com/questions/35337733/getting-value-from-returned-promise-from-async-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!