何时或谁将解析和拒绝函数传递给 JS 承诺? [英] When or who does pass resolve and reject functions to JS promises?

查看:15
本文介绍了何时或谁将解析和拒绝函数传递给 JS 承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始学习 javascript 承诺.但我就是无法理解承诺的概念.最让我烦恼的是,谁将 Resolver 和 Reject 函数传递给 promise 构造函数?

I have begin learning javascript promises. But I just can't understand the concept of promises. The thing that bothers me most is who is passing the Resolver and Reject function to a promise constructor ?

请看这个 Promise 示例:

See this example of Promise:

function getImage(url){
    return new Promise(function(resolve, reject){
        var img = new Image()
        img.onload = function(){
            resolve(url)
        }
        img.onerror = function(){
            reject(url)
        }
        img.src = url
    })
}

现在谁传递了res​​olve和reject方法,因为我对javascript的理解告诉我这个脚本会抛出未知变量错误,因为resolve和rejects没有定义?

Now who does pass resolve and reject methods , as my understanding of javascript says me that this script will throw unknown variable errors as resolve and rejects are not defined ?

getImage('doggy.jpg').then(function(successurl){
    document.getElementById('doggyplayground').innerHTML = '<img src="' + successurl + '" />'
}).catch(function(errorurl){
    console.log('Error loading ' + errorurl)
})

现在你看到了一个类似上面的方法,传递这些方法(解析和拒绝)的唯一方法是通过 then 和 catch ,如上面对 getImage 的方法调用所使用的那样.

Now you see a method like the above , the only way these methods(resolve and reject) are passed are via then and catch as used in above method call to getImage.

推荐答案

最让我烦恼的是谁将 Resolver 和 Reject 函数传递给 promise 构造函数?

The thing that bothers me most is who is passing the Resolver and Reject function to a promise constructor ?

没人.

函数由promise构造函数传递.

The functions are passed by the promise constructor.

它们被传递给作为第一个参数传递给promise构造函数的函数.

They are passed to the function which you pass as the first argument to the promise constructor.

这篇关于何时或谁将解析和拒绝函数传递给 JS 承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆