Error saving a JavaScript promise in a variable

2

How can I save a value of a promise in javascript already tried with this

function loadImage(url){
    return new Promise((resolve, reject) => {
        const image = new Image();
        image.addEventListener('load', () => {
            resolve(image);
        });
        image.src = url;
    });
}
var image = loadImage(image);
image.then(result => {
            return result;
        });

And it does not work I get something like that when I print the variable in the console.

Promise {<pending>}
__proto__
:
Promise
[[PromiseStatus]]
:
"resolved"
[[PromiseValue]]
:
img

But if I print the image variable from the loadImage function inside the promise I get the normal image configuration.

    
asked by FernandoGameYt 18.07.2018 в 04:31
source

1 answer

1

Just as the comment tells you, you can occupy async / await that would be waiting for your image to load and then run the .then ()

function loadImage(url){
    return new Promise((resolve, reject) => {
        const image = new Image();
        image.addEventListener('load', () => {
            resolve(image);
        });
        image.src = url;
    });
}
async function callLoadImage(){
    var image = loadImage(image);
    await image.then(result => {
        return result;
    });
}
    
answered by 18.07.2018 / 22:01
source