0

So I Have My Function Like This

/** @ts-ignore eslint-disable */
declare var require: any
import generateString from "./Strings/GenerateString";
var txtomp3 = require("text-to-mp3");
const fs = require("fs");

export default async function newCaptcha(length: any) {
    let captcha = generateString();
    let binary: AudioBuffer;
    let err;
    txtomp3.getMp3(captcha, async(err: any, binaryStream: any) => {
        binary = binaryStream
    })
    return new Promise((resolve, reject) => {
        resolve(binary)
    })
}

I Have tried logging binaryStream and captcha but they arent undefined whereas when i call the function,

newCaptcha({ length: 1 }).then(binaryStream => {
    console.log(binaryStream)
}).catch(e => {
    console.error(e)
})

It returns undefined

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
Gaurish
  • 89
  • 2
  • 12
  • You are returning your promise to the callback function of `txtomp3.getMp3`, not to the `newCaptcha` function. Move it out of `txtomp3.getMp3`. – Ivar Dec 21 '21 at 08:48
  • I Have tried that, Doesnt help me with that, Checked some more as well, – Gaurish Dec 21 '21 at 08:48
  • 1
    You need to wrap the `getMp3` function call in a promise and return the promise. Then resolve/reject inside the `getMp3` callback. – evolutionxbox Dec 21 '21 at 08:48
  • Edited The Question. So Basically I'm now resolving The Promise outside the function of txttomp3 – Gaurish Dec 21 '21 at 08:52
  • The edit doesn't help. You cannot pass an async function to a callback and expect it to work – evolutionxbox Dec 21 '21 at 08:56
  • Your initial attempt was way closer to an actual solution. The link in my first comment explains how to properly promisify a callback function. Try this: https://jsfiddle.net/ngdt02kj/ (just swapped the `return new Promise` and `txtomp3.getMp3` lines). – Ivar Dec 21 '21 at 08:57
  • 1
    Wrapping it seemed to work! Thanks to both of you! – Gaurish Dec 21 '21 at 09:02

1 Answers1

0

Wrapping the getMp3 inside the promise seemed to work

/** @ts-ignore eslint-disable */
declare var require: any
import generateString from "./Strings/GenerateString";
var txtomp3 = require("text-to-mp3");
const fs = require("fs");

export default async function newCaptcha(length: any) {
    let captcha = generateString();
    let binary: AudioBuffer;
    let err;
    return new Promise<AudioBuffer>((resolve, reject) => {
        txtomp3.getMp3(captcha, function(err: any, binaryStream: AudioBuffer) {
            resolve(binaryStream);
        })
    })
}



Gaurish
  • 89
  • 2
  • 12