簡體   English   中英

如何在node.js中使用promises一個接一個地執行四個命令

[英]How to execute four commands one after other using promises in node.js

我是node.js的新手,我不確定為什么我的以下承諾沒有達到預期的效果。

var command1 = sshCommands.init().catch( (error) => {console.log(error);});
    var command2 = command1.then(sshCommands.plan(filename, size, ipaddr)).catch( (error) => {console.log(error);});
    var command3 = command2.then(sshCommands.apply(filename, size, ipaddr)).catch( (error) => {console.log(error);});
    var command4 = command3.then(strap(filename, ipaddr)).catch( (error) => {console.log(error);});

以下是我要一個接一個觸發的功能。 當前,所有這些都在同一時間啟動。 用給定的代碼

module.exports.init  = () => {
    return new Promise((resolve, reject) => {
        session.execute('ls /opt/myFiles', function (err, code, logs) {
            if (err) {
                console.log(err);
                reject(err);
            } else {
                resolve(code);
            }
        });
    }
)
};

module.exports.plan = (filename, size, ipaddr) => {
    return new Promise((resolve, reject) => {
        session.execute('ls /opt/files', function (err, code, logs) {
            if (err) {
                console.log(err);
                reject(err);
            } else {
                resolve(code);
            }
        });
    }
)
};

module.exports.apply = (filename, size, ipaddr) => {
    return new Promise((resolve, reject) => {
        session.execute('ls /opt/files2', function (err, code, logs) {
            if (err) {
                console.log(err);
                reject(err);
            } else {
                resolve(code);
            }
        });
    }
)
};

我認為您錯過了Node中承諾的要點。 許諾的要點是,當一個人拋出錯誤時,它們中的全部無效。 因此,如果您有[promise1,promise2,promise3]和promise2引發錯誤,promise3將不會自動執行。 建議為NodeJS添加一個類似bluebird的庫。

無論哪種方式,您的代碼都應該這樣完成。

sshCommands.init()
.then(sshCommands.plan(filename, size, ipaddr))
.then(shhCommands.apply(filename, size, ipaddy))
.then(strap(filename. ipaddr))
.catch((err) => {...});

您還可以對實現所返回的內容進行一些評估。

shhCommands.init((e) => {
    console.log(e);
    return shhCommands.plan(filename, size, ipaddr);
}).then(...)...

更一般承諾在這里或以上的藍鳥承諾這里

我已經模擬了測試,以使承諾鏈起作用。 看看是否對您有幫助。

在圖1.1中,它是測試結果,第一個結果是在對command1.init()的調用中未使用await ,第二個結果是具有await

圖1.1 在此處輸入圖片說明

// mochatest

    const command1=require('./init'),command2=require('./plan'), command3=require('./apply');
    describe("asyncTests", () => {
    it("handles Promise rejection",async ()=>{
        var filename, size, ipaddr
        await command1.init().then(function()
            {
                command2.plan(filename, size, ipaddr).then(function(){
                   command3.apply(filename, size, ipaddr); 
                })
                }).catch(function (error){
                    console.log("Error "+error)
                })
    })       
    });

// init.js

module.exports.init  = () => {
    return new Promise((resolve, reject,next) => {
        //session.execute('ls /opt/myFiles', function (err, code, logs) {
        var v=false;
            if (v===true) {
                console.log("init"+v);
                throw new Error("init")
                //reject(v);
                next;
            } else {
                console.log("init"+v);
                resolve(v);
            }
        //});
    }
)
};

// plan.js

module.exports.plan = (filename, size, ipaddr) => {
    return new Promise((resolve, reject,next) => {
       // session.execute('ls /opt/files', function (err, code, logs) {
       var v=false;
            if (v===true) {
                console.log("plan"+v);
                throw new Error("plan")
               // reject(v);
               next;
            } else {
                console.log("plan"+v);
                resolve(v);
            }
       // });
    }
)
};

// apply.js
module.exports.apply = (filename, size, ipaddr) => {
    return new Promise((resolve, reject) => {
       // session.execute('ls /opt/files2', function (err, code, logs) {
       var v=false
            if (v===true) {
                console.log("apply"+v);
                throw new Error("apply")
                reject(v);
            } else {
                console.log("apply"+v);
                resolve(v);
            }
       // });
    }
)
};

@Vladyslav Kochetkov-即使promise2拋出錯誤,promise3也可以執行。 看一下這個例子。 只需將.then鏈接到對promise2拒絕的promise的捕獲。

在此處輸入圖片說明

但是,如果由於測試中的斷言錯誤而導致承諾拒絕(在plan調用的catch塊中,例如assert.equal("Error pln",error)

在此處輸入圖片說明

那么將不會調用promise3

// mochatest
    const assert=require('chai').assert
    const asyncpromise=require('./asyncpromiserejection.js')
    const command1=require('./init'),command2=require('./plan'), command3=require('./apply');
    describe("asyncTests", () => {
    it("handles Promise rejection",async ()=>{
        var filename, size, ipaddr
        await command1.init().then(function()
            {
                command2.plan(filename, size, ipaddr).then(function(){
                   command3.apply(filename, size, ipaddr); 
                }).catch(function (error){
                    console.log("Error "+error)
                }).then(function(){
                   command3.apply(filename, size, ipaddr); 
                })
                }).catch(function (error){
                    console.log("Error "+error)
                })
    })    
    });

// init.js

module.exports.init  = () => {
    return new Promise((resolve, reject,next) => {
        //session.execute('ls /opt/myFiles', function (err, code, logs) {
        var v=false;
            if (v===true) {
                console.log("init"+v);
                throw new Error("init")
                //reject(v);
                next;
            } else {
                console.log("init"+v);
                resolve(v);
            }
        //});
    }
)
};

// plan.js
module.exports.plan = (filename, size, ipaddr) => {
    return new Promise((resolve, reject,next) => {
       // session.execute('ls /opt/files', function (err, code, logs) {
       var v=true;
            if (v===true) {
                console.log("plan"+v);
                throw new Error("plan")
               // reject(v);
              // next;
            } else {
                console.log("plan"+v);
                resolve(v);
            }
       // });
    }
)
};

// apply.js
module.exports.apply = (filename, size, ipaddr) => {
    return new Promise((resolve, reject) => {
       // session.execute('ls /opt/files2', function (err, code, logs) {
       var v=false
            if (v===true) {
                console.log("apply"+v);
                throw new Error("apply")
                reject(v);
            } else {
                console.log("apply"+v);
                resolve(v);
            }
       // });
    }
)
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM