Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

javascript - 需要帮助将回调转换为承诺(Need Help to Convert Callbacks to Promise)

I don't know how to convert this Callback into a Promise (result, error).(我不知道如何将此回调转换为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);
}

  ask by Bruno2020 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(为了使您的函数使用Promise而不是回调,您可以执行以下操作)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...