Javascript函数等待直到完成递归异步函数调用它
问题描述:
有没有一种方法在Javascript中等待另一个函数的完成,它的回调,并基本上“暂停”当前函数的完成,直到那个时候?Javascript函数等待直到完成递归异步函数调用它
例子:
var doSomething = function(callback) {
doSomethingElseAsynchronously(doSomething);
/* Wait until doSomethingElseAsynchronously */
/* is finished and it's callback has completed */
return callback();
};
答
你在想什么的是ES7当前提案所知道的async
functions。其语法如下:
async function doSomething() {
let result = await doThingAsync(); // doThingAsync returns a Promise
// ... Do things ...
return result[0]
}
async
函数返回一个Promise
其解决与函数的最终返回值。
注意async
功能几乎没有任何支持,你应该选择使用它们,您必须首先transpile代码以ES6或ES5采用类似Babel
https://stackoverflow.com/questions/5000415 /调用函数之前的功能是完成 –
[前一个函数完成后调用函数]可能的重复(https://stackoverflow.com/questions/5000415/call-a-function-after -previous-function-is-complete) –
搜索“javascript异步等待”以获得很多答案。 –