为什么这样调用图片加载,promise 内部的后续代码不会执行了?

jsbin - link - demo

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>promise-load</title>
</head>

<body>

    <script>

        function loadImageAsync(url) {
            return new Promise((resolve, reject) => {
                let img = new Image()
                img.src = url
                img.onload(()=>resolve(img))
                img.onerror(()=>reject())
                console.log(3);
            })
        }
        loadImageAsync('https://avatarsabc.githubusercontent.com/u/54520846?s=400&u=5220402538d51b3c67cf208ea16f93cb218fe4d2&v=4').then((imgDom) => {
            console.log('success');
            document.body.appendChild(imgDom)
        }).catch(() => {
            console.log('error-Load');
        })

    </script>
</body>

</html>

为什么console.log(3) 没有执行

阅读 2.2k
1 个回答

onload is not function? 报错了吧。

正确的应该是


img.onload = (()=>resolve(img))
img.onerror = (()=>reject())
推荐问题
logo
Microsoft
子站问答
访问
宣传栏