gpt4 book ai didi

javascript - 异步函数与返回 New Promise

转载 作者:可可西里 更新时间:2023-11-01 01:53:33 26 4
gpt4 key购买 nike

更新

我已经阅读了十几篇关于这个主题的文章,但没有一篇涉及这个基本问题。我将在本文末尾开始列出资源部分。

原帖

我对 async 函数的理解是它返回一个 promise 。

MDN 文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

在我的程序中我可以这样写:

function testPromise() {
return new Promise((resolve, reject) => {
// DO WORK
reject() // IF WORK FAILS
resolve() // IF WORK IS SUCCESSFUL
})
}

async function mainFunction() {
let variable
try {
variable = await testPromise()
} catch(e) {
throw e
}
return variable
}

我还可以将 testPromise 编写为异步函数,并在相同的上下文中编写 await

async function testAsyncFunction() {
//DO WORK AND THROW ERROR IF THEY OCCUR
}

async function mainFunction() {
let variable
try {
variable = await testAsyncFunction()
} catch(e) {
throw e
}
return variable
}

哪个被认为是最佳实践?如果我想创建异步操作,该函数应该使用 return New Promise 并在 async 函数中等待,还是正在等待来自 async 的函数async 功能相同区别?

资源

JavaScript ES 2017:通过示例学习 Async/Await https://codeburst.io/javascript-es-2017-learn-async-await-by-example-48acc58bad65

Javascript — ES8引入async/await函数 https://medium.com/@reasoncode/javascript-es8-introducing-async-await-functions-7a471ec7de8a

JavaScript 的 Async/Await 破坏 Promises 的 6 个原因(教程) https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9

--------------------电流--------------------

export default function time_neo4jUpdate({ store, action, change, args, }) {
return new Promise(async (resolve, reject) => {
try {
const {
thing: { type },
nonValidatedArgs: { leapYear, root, start, end },
_neo4j,
_cypherReducers,
_neo4jCreateReduce,
_timetreeSteps: { update }
} = store.getState()
let results = []
for (let i = 0; i < _neo4jCreateReduce.length; i++) {
const result = await _neo4j.session(
_neo4jCreateReduce[i],
_cypherReducers.runQuery(update, i, root, start, end))
results = [...results, result]
}
resolve({
store,
action: 'NEO4J_UPDATE',
change: results,
args
})
} catch (e) {
const m = `NEO4J TIMETREE UPDATE: Unable to complete the UPDATE step for the timetree. WHAT: ${e}`
reject(m)
}
})
}

--------------------作为异步函数------------------------

export default async function time_neo4jUpdate({ store, action, change, args, }) {
try {
const {
thing: { type },
nonValidatedArgs: { leapYear, root, start, end },
_neo4j,
_cypherReducers,
_neo4jCreateReduce,
_timetreeSteps: { update }
} = store.getState()
let results = []
for (let i = 0; i < _neo4jCreateReduce.length; i++) {
const result = await _neo4j.session(
_neo4jCreateReduce[i],
_cypherReducers.runQuery(update, i, root, start, end))
results = [...results, result]
}
return {
store,
action: 'NEO4J_UPDATE',
change: results,
args
}
} catch (e) {
const m = `NEO4J TIMETREE UPDATE: Unable to complete the UPDATE step for the timetree. WHAT: ${e}`
throw m
}
}

最佳答案

即使没有可用的async/awaityou should very rarely need to use new Promise() .如果您经常使用它,这通常是一种代码味道。

async/await 的全部意义在于,它可以让您避免很多需要显式处理 promises 的情况。

因此,如果您的目标环境支持它(Internet Explorer 不支持 async/await)或者您正在使用转译器,请继续使用它可以在任何地方。这就是它的用途。

请记住,这是毫无意义的:

catch(e) {
throw e;
}

捕捉错误只是为了重新抛出它是没有意义的。因此,如果您实际上没有对捕获的错误执行任何操作,请不要捕获它:

async function testAsyncFunction() {
//DO WORK AND THROW ERROR IF THEY OCCUR
return value
}

编辑:既然您已经提供了代码示例,我可以更加肯定地回答:如果您的功能是基于现有的 promise ,那么无论如何,它很好用async/await 并且您通常不应该使用new Promise():

export default async function time_neo4jUpdate({
store,
action,
change,
args,
}) {
try {
const {
thing: {
type
},
nonValidatedArgs: {
leapYear,
root,
start,
end
},
_neo4j,
_cypherReducers,
_neo4jCreateReduce,
_timetreeSteps: {
update
}
} = store.getState()

const results = await _neo4jCreateReduce.reduce(async function (acc, el) {
const result = await _neo4j.session(
el,
_cypherReducers.runQuery(
update,
i,
root,
start,
end
)
)

return [...(await acc), result]
}, []);

return {
store,
action: 'NEO4J_UPDATE',
change: results,
args
};
} catch (e) {
const m = `NEO4J TIMETREE UPDATE: Unable to complete the UPDATE step for the timetree. WHAT: ${e}`
throw m;
}
}

关于javascript - 异步函数与返回 New Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47047978/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com