Home > database >  Return a promise with async/await inside then
Return a promise with async/await inside then

Time:09-13

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

e.g.

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 e.g.

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}

CodePudding user response:

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.

  • Related