Encapsulate a method A with Promise, and then another method B calls the encapsulated A method, so how does the B method return a Promise object?

function pro(){
    return new Promise(resolve=>{
        resolve()
    })
}

function a(){
    return pro().then(res=>{
        setTimeout(()=>{
           console.log(1)
        },2000)
    })
}

function b(){
    return pro().then(res=>{
        console.log(2)
    })
}

function c(){
    return pro().then(res=>{
        console.log(3)
    })
}

a().then(b).then(c);

//2 3 1

Why isn"t the final result 1 / 2 / 3?
is it correct to return Promise in this way?

Apr.28,2022

because your a method just creates a timer, it doesn't mean that the timer callback is executed.

function a() {
    return pro().then(res => {
        return new Promise((reslove) => {
            setTimeout(() => {
                console.log(1)
                reslove();
            }, 2000)
        })
    })
}

there is nothing wrong with grammar, but I think what you are trying to say is:

function pro() {
    return new Promise(resolve => {
        resolve()
    })
}

function a() {
    return pro().then(res => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log(1); 
                resolve()
            },
            2000)
        })
    })
}

function b() {
    return pro().then(res => {
        console.log(2)
    })
}

function c() {
    return pro().then(res => {
        console.log(3)
    })
}

a().then(b).then(c);

your code, a, immediately returns a promise of resolved, so it goes straight to b without waiting. To output sequentially, you must resolve

in setTimeout The order of

is no problem, except that setTimeout is a macro task and others are micro tasks. For more information, please see https://codeshelper.com/a/11...

.
Menu