Javascript 深度嵌套承诺的替代方案

Javascript 深度嵌套承诺的替代方案,javascript,Javascript,有一系列与密码学相关的操作,我更愿意序列化。然而,这在javascript中似乎根本不可能实现。下面是使用承诺的结果 importKey(pemPriv).then(impPrivKey=> { console.log(`impPrivKey: ${impPrivKey}`) importKey(pemPub,'encrypt').then(impPubKey=> { importKey(pemPriv,'decrypt').then(impPrivK

有一系列与密码学相关的操作,我更愿意序列化。然而,这在javascript中似乎根本不可能实现。下面是使用
承诺的结果

importKey(pemPriv).then(impPrivKey=> {
    console.log(`impPrivKey: ${impPrivKey}`)
    importKey(pemPub,'encrypt').then(impPubKey=> {
        importKey(pemPriv,'decrypt').then(impPrivKey=> {
            console.log(`impPubKey: ${impPubKey}`)
            encrypt(impPubKey  , "hello world!").then(enc => {
                console.log(`encrypted: ${enc}`)
                decrypt(impPrivKey, enc).then(dec => {
                    console.log(`decrypted: ${dec}`)
                })
            })
        })
    })
})

这很难处理:除了处理顺序的
承诺
之外,还有其他方法可以避免渐进式嵌套吗?

只要在异步函数中运行,就可以使用Async/wait

const encryptDecrypt = async (pemPriv) => {

  const impPrivKey = await importKey(pemPriv);
  console.log(`impPrivKey: ${impPrivKey}`);
  const impPubKey = await importKey(pemPub,'encrypt');
  const impPrivKey = await importKey(pemPriv,'decrypt');
  console.log(`impPubKey: ${impPubKey}`);
  const enc = await encrypt(impPubKey  , "hello world!");
  console.log(`encrypted: ${enc}`);
  const dec = await decrypt(impPrivKey, enc);
  console.log(`decrypted: ${dec}`);

}

encryptDecrypt(pemPriv);

承诺链接是您想要的,任何
。然后可以链接返回承诺的
处理程序,但由于您还需要访问过程中的每个结果,因此需要使用闭包来存储中间结果,如下所示:

function decrypt() { 
    const pemPriv = // some private key
    const pemPub = // some public key

    const privateKey;
    const publicKey;

    importKey(pemPriv)
        .then(impPrivKey => {
            console.log(`impPrivKey: ${impPrivKey}`)
            privateKey = impPrivKey;
            return importKey(pemPub, 'encrypt');
        })
        .then(impPubKey => {
            console.log(`impPubKey: ${impPubKey}`)
            publicKey = impPubKey // Optional
            return encrypt(publicKey, "hello world!")
        })
        .then(enc => {
            console.log(`encrypted: ${enc}`)
            return decrypt(privateKey, enc)
        })
        .then(dec => {
            console.log(`decrypted: ${dec}`)
        })
}

decrypt()

延续传球方式就是这样一种选择。thx-我现在正在考虑。看起来你已经这么做了。是的,我想这就是我想要的。筑巢变得很尴尬。这似乎与问题中的基本相同?是否有结构上的变化?请注意每个
。然后
是如何以返回结束的,这允许您将下一个
。然后
向上移动一级,不同之处在于格式设置,但也删除了一系列嵌套,允许您将每个处理程序进一步解耦。代码中的挑战在于,下一个处理程序不仅需要来自前一个处理程序的值,还需要来自前一个处理程序的值,因此我们需要某种方法来跟踪这些值。哦,我看到您为中间结果添加了占位符。我将把这一点作为一个有用的选项进行表决,但将保留@James的线性异步方法作为最直接的答案。完全公平,如果一个人没有异步/等待的访问权限,或者只是想了解更多关于如何使用Promisetally great reading的信息,那么这个答案也很有用