替代深层嵌套的承诺

时间:2020-07-17 19:49:57

标签: javascript

我希望序列化与密码学相关的一系列操作。但是,在javascript中似乎根本不可能。这是使用Promises的结果。

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}`)
                })
            })
        })
    })
})

这很麻烦:处理顺序Promises可以避免渐进式嵌套吗?

2 个答案:

答案 0 :(得分:3)

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

import java.util.function.Function;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;

public class Main{
      public static void main(String args[]){
    
            Function<myData, Property<String>> fStr;
            Function<myData, Property<Integer>> fInt;
        
            fStr = (myData e)-> {return e.getStr();};
            fInt = (myData e)-> {return e.getInt();};
        
         }

    public static class myData {
     
        private final SimpleStringProperty myStr = null;
        private final SimpleIntegerProperty myInt = null;

        public SimpleStringProperty getStr() {
            return myStr;
        }

        public SimpleIntegerProperty getInt() {
            return myInt;
        }
    
    }

}

答案 1 :(得分:3)

您想要的是Promise链,可以将任何返回Promise的.then处理程序链接起来,但是由于您还需要访问每个结果,因此需要使用闭包来存储中间结果,就像这样:

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()