简体   繁体   English

需要帮助将回调转换为 Promise

[英]Need Help to Convert Callbacks to Promise

I don't know how to convert this Callback into a Promise (result, error).我不知道如何将此 Callback 转换为 Promise(结果,错误)。 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它不是 100% 清楚你想要什么,但这是我认为你要求的一个简单例子

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)
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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