Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   return hash undefined (https://javascript.ru/forum/misc/77478-return-hash-undefined.html)

Castromen 11.05.2019 16:20

return hash undefined
 
Добрый день.
Пишу функцию генерацию hah но при вызове ее выдает undefined,
Подскажите плз. где проблема
let t = getHash('Test')

//Вариант 1
export function getHash(p1) {
    let text = "";
    let possible = "abcdefghijklmnopqrstuvwxyz1234567890+=-/!?";
    for (let i = 0; i < 8; i++) text += possible.charAt(Math.floor(Math.random() * possible.length));
    let t = sha256(p1 + text).then(hash => {
        return hash
    }).catch(error => {console.log("Ошибка получение Hash")})

}


//Вариант 2
export function getHash(p1) {
    let text = "";
    let possible = "abcdefghijklmnopqrstuvwxyz1234567890+=-/!?";
    for (let i = 0; i < 8; i++) text += possible.charAt(Math.floor(Math.random() * possible.length));
    let t = sha256(p1 + text).then(hash => {
    }).catch(error => {console.log("Ошибка получение Hash")})
   return t
}

Malleys 11.05.2019 18:46

Цитата:

Сообщение от Castromen
.then(hash => {
    })

У вас получается тип Promise<undefined>

У вас вычисляется скорей UID, чем hash!

async function sha256(message) {
	const encoder = new TextEncoder();
	const data = encoder.encode(message);
	return crypto.subtle.digest("SHA-256", data).then(hexString);
}

function hexString(buffer) {
	const byteArray = new Uint8Array(buffer);

	const hexCodes = [...byteArray].map(value => {
		const hexCode = value.toString(16);
		return hexCode.padStart(2, "0");
	});

	return hexCodes.join("");
}

function getUID(p1) {
	let text = "";
	let possible = "abcdefghijklmnopqrstuvwxyz1234567890+=-/!?";
	for (let i = 0; i < 8; i++) text += possible.charAt(Math.floor(Math.random() * possible.length));
	return sha256(p1 + text).catch(error => { console.log("Ошибка получение UID"); });
}

function getHash(p1) {
	return sha256(p1 + "/7re!t4+").catch(error => { console.log("Ошибка получение Hash"); });
}

(async function main() {
	console.log("Hash", await getHash('Test'));
	console.log("Hash", await getHash('Test'));

	console.log("UID", await getUID('Test'));
	console.log("UID", await getUID('Test'));
})();


Часовой пояс GMT +3, время: 05:49.