Javascript 等待深度异步等待深度函数调用的结果?
我正在使用Javascript 等待深度异步等待深度函数调用的结果?,javascript,node.js,asynchronous,async-await,ecmascript-6,Javascript,Node.js,Asynchronous,Async Await,Ecmascript 6,我正在使用asyncwait通过babel插件将async转换为生成器 在顶层,我正在等待函数响应。然后还有另外两个异步函数func1和func2func2异步检索https://www.google.com 以下脚本返回: go() called func1() called finished func2() called func2() called func2() called 如何仅在成功执行所有调用后才能console.log('finished')?是否可以不使用resolve/r
asyncwait
通过babel插件将async转换为生成器
在顶层,我正在等待函数响应。然后还有另外两个异步函数func1
和func2
func2
异步检索https://www.google.com
以下脚本返回:
go() called
func1() called
finished
func2() called
func2() called
func2() called
如何仅在成功执行所有调用后才能console.log('finished')
?是否可以不使用resolve/reject将它们显式返回为Promise
s
这个例子大大简化了。我尝试做的是递归函数调用,我也会等待
我仍然不确定如何对递归调用执行此操作,但将为其创建一个单独的问题/示例 通过使用
for..of
而不是forEach
可以修复上述示例。内部函数结果不能wait
ed
const rp = require('request-promise')
go()
async function go() {
console.log("go() called")
await func1([1,2,3])
console.log("finished the script")
}
async function func1(arr) {
console.log("func1() called")
for (let item of arr) {
await func2()
}
}
async function func2() {
var res = await rp('https://www.google.com')
console.log("func2() called")
}
我仍然不确定如何对递归调用执行此操作,但将为其创建一个单独的问题/示例 通过使用
for..of
而不是forEach
可以修复上述示例。内部函数结果不能wait
ed
const rp = require('request-promise')
go()
async function go() {
console.log("go() called")
await func1([1,2,3])
console.log("finished the script")
}
async function func1(arr) {
console.log("func1() called")
for (let item of arr) {
await func2()
}
}
async function func2() {
var res = await rp('https://www.google.com')
console.log("func2() called")
}
console.log(“脚本完成”)
没有等待wait func1([1,2,3])
?您也可以使用Promise.all()
在同一个函数中可以有两个wait
s吗?如果是,您可能必须从forEach
循环中删除async
关键字。(我从未使用过async/await)@guest271314在我的原始代码中,有递归函数调用,其中一个调用依赖于前一个调用的结果。Promise.all()
应该能够进行递归调用。请看,async/await没有“deep”。您必须从每个异步函数返回承诺,才能等待它,这是无法避免的。包括接受异步回调的函数。console.log(“完成脚本”)
不等待wait func1([1,2,3])
?您也可以使用Promise.all()
在同一个函数中可以有两个wait
s吗?如果是,您可能必须从forEach
循环中删除async
关键字。(我从未使用过async/await)@guest271314在我的原始代码中,有递归函数调用,其中一个调用依赖于前一个调用的结果。Promise.all()
应该能够进行递归调用。请看,async/await没有“deep”。您必须从每个异步函数返回承诺,才能等待它,这是无法避免的。包括接受异步回调的函数。