异步功能与返回新承诺

Kai*_*nan 13 javascript promise async-await

UPDATE

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

原始邮政

我对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
}
Run Code Online (Sandbox Code Playgroud)

我也可以将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
}
Run Code Online (Sandbox Code Playgroud)

哪个被认为是最佳做法?如果我想创建异步操作,函数是否应该在函数中使用return New Promise和等待,async或者正在等待async函数的async函数有相同的区别?

资源

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

- - - - - - - - - - - 当前 - - - - - - - - - - -

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)
    }
  })
}
Run Code Online (Sandbox Code Playgroud)

---------------------- 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
  }
}
Run Code Online (Sandbox Code Playgroud)

JLR*_*she 6

即使没有async/ await您也很少需要使用new Promise()。如果您经常使用它,通常是代码的味道。

async/ 的全部要点await是,它使您避免了很多情况下可能需要显式使用promise的情况。

因此,如果您要定位的环境中支持它(Internet Explorer不支持async/ await),或者您正在使用翻译器,请继续在任何可能的地方使用它。那就是它的目的。

请记住,这是没有意义的:

catch(e) {
    throw e;
}
Run Code Online (Sandbox Code Playgroud)

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

async function testAsyncFunction() {
  //DO WORK AND THROW ERROR IF THEY OCCUR
  return value
}
Run Code Online (Sandbox Code Playgroud)

编辑:现在,您已经提供了代码示例,我可以更加肯定地回答:如果您的函数基于现有的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;
    }
}
Run Code Online (Sandbox Code Playgroud)