I want to return the array with Promise.

Asked 2 years ago, Updated 2 years ago, 60 views

Thank you for your help.
Please tell me how to handle Promise return values.

■What you want to do
I want to get the value of the array that Promise processed.

■ Program
Access the path of the image written in the external JSON file and convert it to Base64 Image (repeated 5 times).← OK up to here
I plan to pass the converted Base64 Image string (←here) and display the image in PDF.

■What you can't do

in the following program: where myData,

img_image01:base64,iVBORw0KG(…omitted…)'
img_image02:base64,iVBORw0KG(...omitted...)'
img_image03:base64,iVBORw0KG(...omitted...)'

I can pass the Base64 Image string like this, but

console.log(resolvedata)

Then,

Promise{[PromiseStatus]]: "resolved", [[PromiseValue]]: Array(1)}

and Promise wrapped (as per the documentation).

Array(1)

I'd like to take out only the part and use it as an array.
For example,

resolvedata ['img_image01']

If so,

'data:image/png; base64, iVBORw0KG(...omitted...)'

is the image that returns.

//-------------------------------------------------------------------------------
// Convert images in order with Promise and store them in myData
// ------------------------------------------------------------
var resolvedata=getContent().then((myData)=>{
    getBase64Image(myData[0]['path_img'], myData[0]['image01', myData);
    return myData;
}).then(myData)=>{
    getBase64Image(myData[0]['path_img'], myData[0]['image02', myData);
    return myData;
})

        (…omitted…)

.then((myData)=>{
    getBase64Image(myData[0]['path_img'], myData[0]['image05', myData);
    return myData;
}).catch()=>{console.log('error')});


// ------------------------------------------------------------
// Import an external JSON file with the image path written on it and store it in myData (Promise)
// ------------------------------------------------------------
function getContent() {
    return new Promise ((resolve, reject) = > {
        httpObj = new XMLHttpRequest();
        httpObj.open('get','(any file).json',true);
        httpObj.send(null);    
        httpObj.onload=function(){
            var myData=JSON.parse(this.responseText);
            resolve(myData);
        }
    });
}

// ------------------------------------------------------------
// Convert file to Base64 (then)
// ------------------------------------------------------------
function getBase64Image(imgpath,imgfile,myData){
    return new Promise((res,rej)=>{
        if(imgfile=='){
            res();
        } else{
            var path = imgpath;
            var thisimagekey='img_'+imgfile.split('.')[0];
            vargetimg='(any URL)'+path+'/'+imgfile;

            varencoding=false;
            if(encoding)return;
            encoding = true;

            varxhr = new XMLHttpRequest();
            xhr.open('GET', getimg);
            xhr.responseType='arraybuffer';
            xhr.send(null);

            xhr.onload=()=>{
                var array_buffer = xhr.response;
                Base64_From_ArrayBuffer_Async(array_buffer, function(base64){
                    vardata_url='data:'+xhr.getResponseHeader('Content-Type')+';base64,'+base64;    
                    myData[0][thisimagekey]=data_url;    
                });    
                res(myData);    
            };
        }
    });
}

// ------------------------------------------------------------
// Convert to Base64
// ------------------------------------------------------------
functionBase64_From_ArrayBuffer_Async(ary_buffer, callback, increment){
    vardic = [
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
        'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
        'w', 'x', 'y', 'z', '0', '1'', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
    ];
    varbase64="";
    variable_u8 = new Uint8 Array(ary_buffer);
    var num =ary_u8.length;
    varn = 0;
    varb = 0;

    if(increment===undefined) {
        increment=10240;
    }

    vari = 0;
    varj = 0;
    function f(){
        while(i<num){
            b=ary_u8[i];
            base64+=dic[(b>>2)];
            n = (b&0x03)<<4;
            i++;
            if(i>=num)break;

            b=ary_u8[i];
            base64+=dic[n|(b>>4)];
            n = (b&0x0f)<<2;
            i++;
            if(i>=num)break;

            b=ary_u8[i];
            base64+=dic[n|(b>>6)];
            base64+=dic[(b&0x3f)];
            i++;

            j+=3;
            if(j>increment){
                j = 0;
                setTimeout(f,1);
                return;
            }
        }

        varm = num%3;
        if(m){
            base64+=dic[n];
        }
        if(m==1){
            base64+="==";
        } else if(m==2){
            base64+="=";
        }
        callback (base64);
    }
    setTimeout(f,1);
}

What should I write to retrieve myData?
Thank you for your cooperation.

javascript promise

2022-09-30 21:27

1 Answers

(Excuse me for my poor Japanese)

To fix it easily, if you change each .then like this, it will work almost as expected:

Returns //v--getBase64Image
.then(myData)=>getBase64Image(myData[0]['path_img'], myData[0]['image01', myData))
.then(myData)=>getBase64Image(myData[0]['path_img'], myData[0]['image02', myData))

And finally, I'll do this

resolveData.then(result=>console.log(result));

The most wrong thing is that I have created a promise on getBase64Image() and I am not waiting for the promise result. If I return promise within then, the next then will be executed after the promise process is completed.

To add a little more, there is a way to write the above code a little more neatly.

I've done very similar things five times, but I can use Promise.all to treat the array a little more like an array for parallel processing.(And parallel processing can make it a little faster)

getContent().then(myData)=>
    // Wait for all getbase64 Images
    Promise.all([1,2,3,4,5].map(num=>) 
        getBase64Image(myData[0]['path_img'], myData[0]['image0'+num], myData)
    ))
    .then()=>myData)
.then(myData)=>{
    console.log(myData);
});


2022-09-30 21:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.