Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

function - JavaScript promise trouble

Here's the function:

    function load_img(url) {
        return new Promise((resolve, rejected) => {

            const img = new Image();
            img.height = 250;
            img.src = url;
            document.body.append(img);
            img.addEventListener("load", () => {
                resolve("LOL");
            });
            img.addEventListener("error", () => {
                rejected();
            });

        });
    }

Here's the function call:

        load_img(url1)
        .then((mes) => {
            console.log(mes);
            return load_img(url2);
        })
        .then((mes) => {
            load_img(url3);
            console.log(mes);
        })
        .catch(() => console.log("Some error"))

I can't understand why should I use in the first then return before the function, function has already return promise in its body, but when we use it without return in then, second then won't get any value, which is stated in the resolve().

Please, help me out!:)

question from:https://stackoverflow.com/questions/65880135/javascript-promise-trouble

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

1 Answer

0 votes
by (71.8m points)

The mes argument in your 2nd .then() comes from the return value of the first .then() handler. If you don't return anything from that first .then() handler, then you don't get any resolved value in the 2nd .then() handler and mes will be undefined.

Plus, the 2nd .then() handler will only "wait" for the load_img(url2) to resolve if you return its promise from within the first .then() handler. This is how you properly chain promises.


Perhaps you're just using this code for testing, but you do not have to load your two images in sequence since the 2nd one does not depend upon the first one. You could load them in parallel and use Promise.all() to know when they are both done.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...