javascriptpromiseresolve

How to get promise result in this case


I must fill a table with the data that I bring from the call to an api, after this call another api (QRCODES) to generate a Qr image with that data.

the problem is that in the resulting array to pass to the table the field where the address to the image should go (qr code) I am getting a "promise" object

    const setTable = async () => {
        console.log(selectedChannel);
        productsService.getProducts(selectedChannel.name, selectedCategory.id).then(data => {
            setProducts(data.data)
            const dataTable = []
            const allArray = data.data
            console.log(allArray)
            let row = {}
            let link = ''
            let qrImage = ''


            allArray.forEach(product => {
                link = "https://motitools.deco.cl/" + selectedChannel.name + "/es-CL/products/" + product.slug
                qrImage = QRCode.toDataURL(link)
                row =  { "imagenQr": qrImage, "category": product.category, "name": product.name, "price": product.price, "image": product.image }
                dataTable.push(row)
            });
            console.log(dataTable)
            setTableConten(dataTable)
        });

The result of qrImage = QRCode.toDataURL(link)

imagenQr: Promise
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAL

how can i get the value of [[PromiseResult]]?.

Usefull info: 1.- make: qrImage = await QRCode.toDataURL(link) gives me this error console error

2.- make QRCode.toDataURL(link).then( data => console.log(data)) return all the codes in console, how set a variable with this value ?

enter image description here

im new on javascript


Solution

  • You can use await, but not in the non async callback. Mixing then with async is rarely a good idea. So drop the .then call, and use await instead, and make the inner callback async.

    Some other remarks:

    const setTable = async () => {
        const {data} = await productsService.getProducts(selectedChannel.name, selectedCategory.id);
        setProducts(data);
    
        const dataTable = await Promise.all(data.map(async ({slug, category, name, price, image}) => {
            const link = "https://motitools.deco.cl/" + selectedChannel.name + "/es-CL/products/" + slug
            const qrImage = await QRCode.toDataURL(link);
            return { "imagenQr": qrImage, category, name, price, image };
        }));
        setTableConten(dataTable);
    };