简体   繁体   中英

Return a promise with async/await inside then

Im quite familiar with javascript but I'm a bit confuse with Promise, Async/Await

How do I add async/await to modify a promise data and return the original Promise

eg

this working fine

function test() {
    const data = {
        sample: 1,
        test: 2
    }

    const prom = Promise.resolve(data)

    prom.then(  data => {
        data.sample =  5
    })
    return prom
}

test().then( data => {
    console.log( data )
})
//output: {sample: 5, test: 2}

but if I do async/await to modify the promise data, the original data seems to output before the promise is modified eg

function test() {
    const data = {
        sample: 1,
        test: 2
    }

    const prom = Promise.resolve(data)

    prom.then( async data => {
        data.sample = await  5
    })
    return prom
}

test().then( data => {
    console.log( data )
})
//output: {sample: 1, test: 2}

this working fine

Not when the promise rejects, no. When using then , you should return the new promise for further chaining, and resolve it with the modified value; you should not mutate values in a promise. So instead of

prom.then(  data => {
    data.sample =  5
})
return prom

better write

return prom.then(data => {
    data.sample = 5
    return data
})

If you carried over this pattern to the async version, it would just work as well - but really, when using async / await , there is no reason to use .then() ! Better write

const data = await prom;
data.sample = await something;
return data;

and mark the test function itself as async .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM