5
提案された非同期/待機構文に慣れてきて、直感的ではない動作があります。 "async"関数の中で、console.logに正しい文字列を付けることができます。しかし、その文字列を返そうとすると、代わりに約束が返されます。非同期関数から返された約束から値を取得する
async/await implicitly returns promise?をチェックすると、「非同期関数()」は約束であって、値ではないことは明らかです。それはいいです。しかし、あなたはどのように価値にアクセスできますか?唯一の答えが「コールバック」の場合、それは問題ありませんが、よりエレガントなものがあることを期待していました。
がmakeHash('password').then(hash => console.log(hash));
それとももちろん、あなたはそれを待って、他の非同期機能を行うことができます:
it('should generate a hash', async function(){
var hash = await makeHash('password');
console.log("inside test: ", hash);
should.exist(hash);
})
があり
// 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"] }
@ JoachimIsaksson:* async関数内のみです。 –