简体   繁体   English

然后返回带有 async/await 的 promise

[英]Return a promise with async/await inside then

Im quite familiar with javascript but I'm a bit confuse with Promise, Async/Await我对 javascript 非常熟悉,但我对 Promise、Async/Await 有点困惑

How do I add async/await to modify a promise data and return the original Promise如何添加 async/await 来修改 promise 数据并返回原始 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但是如果我做 async/await 来修改 promise 数据,则在修改 promise 之前,原始数据似乎是 output

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.当 promise 拒绝时,不会。 When using then , you should return the new promise for further chaining, and resolve it with the modified value;使用then时,您应该返回新的 promise 以进行进一步的链接,并使用修改后的值解决它; you should not mutate values in a promise.你不应该改变 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() !如果您将此模式延续到async版本,它也可以正常工作 - 但实际上,当使用async / await时,没有理由使用.then() Better write写得更好

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

and mark the test function itself as async .并将test function 本身标记为async

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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