简体   繁体   中英

.then() resolves itself before internal promise resolves

I have a promise chain that calls the function pngQuant

.then(response => {
    console.log(response);
    pngQuant.pngQuant(testObj['pngquant']);
}, err =>console.log(err))
//Then upload images
.then(response => {console.log(response)},err=>console.log(err));


function pngQuant(JSON){
    return new Promise((resolve,reject)=>{
        var execString = "find " + pathresolve('./src/resizer/tmp/') + " -name '*.png'"
        execString += " -exec " + pathresolve('./lib/pngquant') + " --force --ext=.png";

        exec(execString,(err,stdout,stderr)=>{
            if(err){
                console.log(err);
                reject(stderr);
            }

            else{
                console.log("resolved");
                resolve("Compression Complete");
            }

        })
    });
}

However the second 'then' in the chain resolves itself and console logs 'undefined', and then immediately after, the console log in the pnqQuant function gets called, meaning that the then is resolved before the pngQuant resolve function is called.

Return the promise created by calling pngQuant from the first then :

.then(response => {
    console.log(response);
    return pngQuant.pngQuant(testObj['pngquant']); // we returned the promise from pngQuant
}, err =>console.log(err))
// then upload images
.then(response => {
  console.log(response);
}, err => console.log(err));

Check the doc of then here

The return statement was causing an issue.

.then(response => {
    console.log(response);
    pngQuant.pngQuant(testObj['pngquant']); 
}, err =>console.log(err))
// then upload images
.then(response => {
  console.log(response);
}, err => console.log(err));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM