.then()在内部promise解析之前自行解析

时间:2018-01-05 03:19:36

标签: javascript ecmascript-6 promise es6-promise

我有一个调用函数pngQuant

的promise链
.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");
            }

        })
    });
}

然而第二个'然后'在链中解析自身和控制台日志' undefined',然后立即调用pnqQuant函数中的控制台登录,这意味着在调用pngQuant resolve函数之前解析then。

2 个答案:

答案 0 :(得分:1)

通过从第一个promise调用pngQuant返回创建的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));

检查doc of then here

答案 1 :(得分:0)

退货声明导致了问题。

Thread