首页 > 解决方案 > 为什么承诺同时执行而不是按顺序执行?

问题描述

function page() {
    return new Promise((resolve, reject) => {
        setTimeout(function() {
            fo = $("#root>div>div>main>div>div:nth-child(3)>div>div:nth-child(2)>div>div>div:nth-child(2)>div:nth-child(2)>div>div:nth-child(2)>div>div:nth-child(2)>div>ul>li:nth-last-child(1)")
            fo.click()
            console.log('翻页')
            resolve();
        }, 200)
    })
}
function l() {
    for (let i = 0, p = Promise.resolve(); i < 10; i++) {
        p = p.then(() => {
                return new Promise(resolve =>
                    setTimeout(function() {
                        console.log('wo')
                        $('#root>div>div>main>div>div:nth-child(3)>div>div:nth-child(2)>div>div>div:nth-child(2)>div:nth-child(2)>div>div:nth-child(2)>div>div:nth-child(1)>div:nth-child(1)>table>tbody>tr>td:nth-child(7)>div>div:nth-child(2)>a>span').eq(i).click()
                        resolve();
                    }, 200)
                )
            })
            .then(() => {
                    return new Promise(resolve =>
                        setTimeout(function() {
                            console.log('wocao')
                            $('body>div:nth-last-child(1)>div>div>div:nth-child(3)>div:nth-child(2)>button>span').click()
                            resolve();
                        }, 200)
                    )
                }
            )
    }
}
Promise.resolve().then(l).then(page)

为什么程序没有按照承诺的顺序运行?我怎么解决这个问题?我已经尝试了很多次,但它们仍然一起执行,但不是按顺序执行。有人可以教我吗?很感谢。

标签: javascript

解决方案


Yourfunction l是一个单位函数(即不返回任何内容),因此不可等待,因为它不返回 a Promise(显式地或通过标记为async)。

你应该:

function l() {
    let p = Promise.resolve() // this needs to exist out of the loop scope
    for (let i = 0; i < 10; i++) {
        p = p.then( /* ... */ )
    }
    return p; // <-- so it can be returned here
}

推荐阅读