异步功能与返回新承诺

时间:2017-11-01 03:55:11

标签: javascript promise async-await

更新

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

原始帖子

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

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函数的相同差异?< / p>

资源

JavaScript ES 2017:通过示例学习异步/等待 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等待承诺的6个理由(教程) https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec10518dd9

---------------------- CURRENT ----------------------

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)
    }
  })
}

---------------------- AS ASYNC FUNCTION ----------------------

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
  }
}

1 个答案:

答案 0 :(得分:4)

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

async / await的重点在于它允许您避免许多情况,否则您需要明确地使用承诺。

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

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

catch(e) {
    throw e;
}

重新抛出错误就没有意义。因此,如果您实际上没有对捕获的错误做任何事情,请不要抓住它:

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

编辑现在您已经提供了代码示例,我可以更加确定地回答:如果您的功能基于现有的承诺,那么无论如何,使用它都是好的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;
    }
}