Node.js 如何同步节点中的两个异步调用?
我用Python和Javascript(在浏览器中)开发(业余级别)。我逐渐接受并喜欢JS的异步特性,加上一个反应式框架,它创造了奇迹 我现在尝试使用NodeJS来替换服务器上的Python脚本。程序的一般流程是获取(HTTP)几个API,一旦我拥有了所有API,就可以做一些事情。这非常适合Python,在Python中,我只需连续调用并收集结果。性能和时间并不重要 当NodeJS文档讨论时,我认为浏览器中JavaScript的异步特性在NodeJS中非常常见。具体地说,在我的例子中,Node.js 如何同步节点中的两个异步调用?,node.js,multithreading,asynchronous,synchronization,thread-synchronization,Node.js,Multithreading,Asynchronous,Synchronization,Thread Synchronization,我用Python和Javascript(在浏览器中)开发(业余级别)。我逐渐接受并喜欢JS的异步特性,加上一个反应式框架,它创造了奇迹 我现在尝试使用NodeJS来替换服务器上的Python脚本。程序的一般流程是获取(HTTP)几个API,一旦我拥有了所有API,就可以做一些事情。这非常适合Python,在Python中,我只需连续调用并收集结果。性能和时间并不重要 当NodeJS文档讨论时,我认为浏览器中JavaScript的异步特性在NodeJS中非常常见。具体地说,在我的例子中,fetch
fetch
到节点的端口是基于承诺的,我们需要经历很多困难才能进行这样的调用
我应该如何同步调用以最终对所有收集的结果采取行动?我有类似的代码
fetch(urlOne)
.then(res => res.json())
.then(res => a = res.a)
fetch(urlTwo)
.then(res => res.json())
.then(res => b = res.b)
// here comes the moment when both a and b are to be used
我可以将一个fetch
与另一个链接起来(在第一个.then()
),但这会分散脚本的主要机制:“geta
,getb
和“用它们做点什么”)具体来说,是否有类似Python的东西等待线程结束(阻止主线程)?
请注意,我理解并欣赏浏览器中JavaScript的异步方法。有一个输出(渲染的DOM)感觉非常自然,当某些元素可用时,它会异步地用它们更新。这对于后端服务(如web服务器)也很有用。然而,在我的例子中,这些活动是非常线性的(或者,这是我问题的核心,需要在某个时候同步)您可以使用这个方法 注:蓝知更鸟是兼容的。这意味着您可以安全地将其与Promise类一起使用,或者替代Promise类中的内置 在我的项目中,我通常使用Bluebird覆盖Promise类
global.Promise = require('bluebird');
您可以使用等待多个异步函数
let firstAsync = fetch(urlOne)
.then(res => res.json())
.then(res => res.a)
let secondAsync = fetch(urlTwo)
.then(res => res.json())
.then(res => res.b)
Promise.all([firstAsync, secondAsync]).then(() => {
// here comes the moment when both a and b are to be used
)
简单地说,您可以使用异步npm包处理大量的内容。它可以并行或同时运行您的函数,当所有函数完成后,将返回带有所有结果的最终回调。正确的方法确实是使用
Promise.all
,但不需要then
调用产生副作用(写入变量,回调结束)all
以数组的形式(与调用的顺序相同)提供结果作为其分辨率值:
Promise.all([
fetch(urlOne)
.then(res => res.json())
.then(res => res.a) // <== No `a =` here
,
fetch(urlTwo)
.then(res => res.json())
.then(res => res.b) // <== No `b =` here
]).then(([a, b]) => { // <== Destructured parameter picking out the first
// and second entries of the array argument
// here comes the moment when both a and b are to be used
});
Promise.all()
是您如何知道何时完成了多个承诺的方法。签出框架中有大量有用的承诺帮助程序。此答案已在上提到。很有趣。你甚至可以在最后加入解构:。然后({a,b})=>{/*在这里使用a和b*/})代码>
Promise.all([
fetch(urlOne)
.then(res => res.json())
.then(res => res.a) // <== No `a =` here
,
fetch(urlTwo)
.then(res => res.json())
.then(res => res.b) // <== No `b =` here
]).then(([a, b]) => { // <== Destructured parameter picking out the first
// and second entries of the array argument
// here comes the moment when both a and b are to be used
});