简体   繁体   中英

Need Help to Convert Callbacks to Promise

I don't know how to convert this Callback into a Promise (result, error). Can you show me how it's made and explain with comments?

function calcular() 
{
        let conta = 0;;
        var N1 = parseInt(document.getElementById("num1").value);
        var opção = document.getElementById("op").value;
        var N2 =  parseInt(document.getElementById("num2").value);

        if (opção === "+")
        {
            conta = N1 + N2;

        }
}

function MostrarResultado(conta) 
{

    document.getElementById("result").innerHTML = "O resultado da sua conta é = " + conta;

}

function Executar(callback)
{
    callback(calcular());
}

function xpto()
{
    setTimeout(function() {Executar(MostrarResultado)}, 3000);
}

its not 100% clear on what you want but here is a quick example of what i think your asking for

so to make your function use promises instead of callback you could do something like this

function promiseFunction(){
    return new Promise(resolve =>{
        resolve(result);
    }
}

and when you want to get the data that the function returns you could do this

function getInfoFromFunction(){
    promiseFunction(arg).then(result => {
        console.log(result)
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM