简体   繁体   English

Javascript函数等到其中调用的递归异步函数完成

[英]Javascript function wait until completion of recursive asynchronous function called within it

Is there a way in Javascript to wait for the completion of another function and it's callback and essentially "pause" the completion of the current function until that time? Javascript中是否有办法等待另一个函数的完成及其回调,并在此之前实质上“暂停”当前函数的完成?

Example: 例:

var doSomething = function(callback) {
  doSomethingElseAsynchronously(doSomething);
  /* Wait until doSomethingElseAsynchronously */
  /* is finished and it's callback has completed */
  return callback();
};

What you're thinking of is a current proposal in ES7 know as async functions . 您正在考虑的是ES7中的当前建议,即async功能 Their syntax looks like this: 它们的语法如下所示:

async function doSomething() {
    let result = await doThingAsync(); // doThingAsync returns a Promise
    // ... Do things ...
    return result[0]
}

async functions return a Promise which resolve with the eventual return value of the function. async函数返回一个Promise ,该Promise将使用函数的最终返回值进行解析。

Note that async functions have little to no support, and should you choose to use them, you must first transpile your code to ES6 or ES5 using something like Babel 请注意, async功能几乎没有支持,如果您选择使用它们,则必须首先使用Babel之类的代码将代码转换为ES6或ES5

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

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