本文介绍了在使用Node.js的Promise中避免回调地狱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用诺言在nodejs中编写了大约六个函数,我想真正发布所有这些代码,相反,我将发布一个模拟示例,以便我可以简单地封装我的问题。所以说我下面有2个函数:

I have written about a half a dozen functions in nodejs using promises, i want really post all of that code, instead i will post a simulated example , so i can encapsulate my problem succinctly. so say i have 2 functions below:

foo = () => {
    return new Promise( ( r , rj ) => {
       setTimeout( () => {
             r('DONE');
       }, 3000 );
    });
}

bar = () => {
    return new Promise( (r , rj) => { r('ALL DONE !') } )
}

现在我想避免回调地狱,并执行以下操作:

Now i would like to avoid the callback hell and do the following:

foo().then( (resp) => console.log(resp) ).bar()

相反,我被迫这样做:

foo().then( (resp) => { console.log(resp); bar() } )

所以基本上在我的生产代码中我有类似到目前为止,以下内容(只是给您一个想法):

So basically in my production code i have something like the below, so far(just to give you an idea):

let uploadToVault = ( INPUT_DIR , VOLT_CRED ) => {

    INPUT_DIRECTORY = INPUT_DIR;
    VOLT_CREDENTIALS = VOLT_CRED;

    volt_APILogin().then( () => {
        volt_getProduct().then( () => {
           volt_CreatePresentation().then( (resp) => {
                console.log(resp);
                volt_uploadSlides().then( (resp) => {
                    console.log(resp);
                    volt_bindSlide().then( (resp) => {
                        console.log(resp);
                    });
                });
           });
        });
    });
}

现在我如何用链式格式写这个而不是用callback?

Now how can i write this in more a chain format vs writing this in a callback ?

推荐答案

想法是始终返回承诺:

volt_APILogin()

    .then(() => {
        return volt_getProduct();
    })
    .then(() => {
         return volt_CreatePresentation();
    })
    .then((resp) => {
         console.log(resp);
         return volt_uploadSlides();
    })
    .then((resp) => {
         console.log(resp);
         return volt_bindSlide();
    })
    .then((resp) => {
         console.log(resp);
         return Promise.resolve('just for fun');
    })
    .then((resp) => {
         console.log("This round is", resp);
    });

然后,如果需要使用中间值,则只需将它们收集到外部变量中链。

Then, if there are intermediary values you need to use down the chain, just collect them to variables outside the chain.

这篇关于在使用Node.js的Promise中避免回调地狱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:04