天气君
天气君

Reputation: 97

Why are the promises excute at the same time and not in order?

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)

Why is the program working not in order of the promises? How can I solve this problem? I've tried many times but they still execute together but not in order. Could somebody teach me? Very thanks.

Upvotes: 0

Views: 59

Answers (2)

spender
spender

Reputation: 120400

Your function l is a unit function (i.e. returns nothing) and is therefore not awaitable as it does not return a Promise (either explicitly, or via being marked as async).

You should:

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
}

Upvotes: 1

Lajos Arpad
Lajos Arpad

Reputation: 76436

You need to resolve inside the timeout

new Promise(function(resolve, reject) {
  // the function is executed automatically when the promise is constructed

  // after 1 second signal that the job is done with the result "done"
  setTimeout(() => {console.log("done");resolve()}, 1000);
}).then(function (res2, rej2) {
  setTimeout(() => {console.log("done2")}, 1000);
})

but in your case you do not define parameters to the promise, hence they are default.

Upvotes: 0

Related Questions