gpt4 book ai didi

node.js - 如何让函数调用等待另一个函数调用完成

转载 作者:IT老高 更新时间:2023-10-28 12:29:36 26 4
gpt4 key购买 nike

所以我想要的是,

functionA(); // this completes 
functionB(); // then this runs

我试图一次将多个集合播种到数据库中,当我按程序将每个集合一个接一个地放置时,只有最后一个被播种到数据库中。我试图弄清楚如何让 Javascript 不异步,所以我可以让每一步都等到前一步完成。我觉得我可以使用下划线“延迟”方法,该方法延迟调用函数,直到当前调用堆栈被清除;我只是不知道如何使用它。

我正在使用下划线延迟方法,它有效,但它取决于种子大小,我想摆脱它。

代码如下所示:

// creates and sends seed data to a collecion("blah") inside a db("heroes")
var blog = MeanSeed.init("heroes", "blah");
blog.exportToDB();

// this waits a second till it starts seeding the "heroes" DB with its "aliens" collection
_.delay(function() {
var user = MeanSeed.init("heroes", "aliens");
user.exportToDB();
}, 1000)

最佳答案

我可以推荐使用 Promises .这是相当新的,它是在 ES6 中引入的(但它已经在 Node 5-6 中)。使用示例:

new Promise(function(resolve, reject){
// do something in A
resolve();
}).then(function(result) {
// do something else in B
return result;
})

关于node.js - 如何让函数调用等待另一个函数调用完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37399106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com