完成一个诺言,然后在下一个诺言之前,在一个长列表中



我最近发现了JavaScript承诺。广告的好处是通过链条然后条款进行干净的筑巢。

我的代码按预期工作,但是嵌套的增长与使用回调时一样丑陋。是否有更好的方法可以使用链接来删除所有这些嵌套?请注意,我需要任务n才能完成,然后任务n 1中的任何内容。

非常简单的固定示例

'use strict';
function P1() {
    return new Promise((resolve) => {
        console.log("starting 1")
        setTimeout(() => {
            console.log("done 1")
            resolve();
        }, 100)
    })
}
function P2() {
    return new Promise((resolve) => {
        console.log("must start 2 only after 1 is done")
        setTimeout(() => {
            console.log("done 2")
            resolve();
        }, 50)
    })
}
function P3() {
    return new Promise((resolve) => {
        console.log("must start 3 only after 3 is done")
        setTimeout(() => {
            console.log("done 3")
            resolve();
        }, 10)
    })
}
console.log("this works, but if list was long, nesting would be terribly deep");
// start 1, done 1, start 2, done 2, start 3, done 3.
P1().then(() => {
    P2().then(() => {
        P3()
    })
})

基于我应该完成的反馈

P1().then(() => {
    return P2()
}).then(() => {
    return P3()
}).catch(() => { console.log("yikes something failed" )})

真实代码接收一系列内容以顺序处理。仅当步骤序列指定为代码时,上面建议的格式才适合。似乎应该有某种诺言。如下:

'use strict';

function driver(single_command) {
    console.log("executing " + single_command);
    // various amounts of time to complete command
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log("completed " + single_command);
            resolve()
        }, Math.random()*1000)
    })
}
function execute_series_of_commands_sequentialy(commands) {
    var P = driver(commands.shift());
    if (commands.length > 0) {
        return P.then(() => { return execute_series_of_commands_sequentialy(commands) })
    } else {
        return P
    }
}
execute_series_of_commands_sequentialy([1, 2, 3, 4, 5, 6, 7, 8, 9]).then(() => {
    console.log("test all done")
})
P1()
.then(() => P2())
.then(() => P3())

您可以使代码更平坦。另外,明确的结构是一个对抗

您误解了承诺如何工作。您可以链返回值以及承诺实例,并沿着链条进一步传递:

P1()
.then(() => P2())
.then(() => P3())

无需筑巢。

我个人喜欢这种格式的外观,并且是我使用的

foo(){
  P1().then(()=>{
    return P2();
  }).then(()=>{
    return P3();
  }).catch((err)=>{
    //handle errors
  });
}

有一个大大简化承诺写作的异步/等待。

JavaScript的异步/等待打击承诺

基本上,它在编写异步函数上像同步代码一样:

async function P(number) {
    return new Promise((resolve) => {
        console.log("starting "+number)
        setTimeout(() => {
            console.log("done "+number)
            resolve();
        }, 800)
    })
}
/* Or the ES6 version :
  const P = async (number) => new Promise((resolve) => { ... })
*/
async function run(){
   await P(1)
   await P(2)
   await P(3)
   
   console.log("All done!")
}
run()

最新更新