如何更改以下代码,以便触发异步操作并同时运行?
const value1 = await getValue1Async();
const value2 = await getValue2Async();
// use both values
Run Code Online (Sandbox Code Playgroud)
我需要做这样的事情吗?
const p1 = getValue1Async();
const p2 = getValue2Async();
const value1 = await p1;
const value2 = await p2;
// use both values
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用node.js中的Q模块来了解promises,但是我有一个小问题.
在这个例子中:
ModelA.create(/* params */)
.then(function(modelA){
return ModelB.create(/* params */);
})
.then(function(modelB){
return ModelC.create(/* params */);
})
.then(function(modelC){
// need to do stuff with modelA, modelB and modelC
})
.fail(/*do failure stuff*/);
Run Code Online (Sandbox Code Playgroud)
.create方法在每个.then()中返回一个promise,正如预期的那样,获取promise的已解析值.
但是在最后的.then()中,我需要拥有所有3个先前解析的promise值.
最好的方法是什么?
我是承诺并使用NodeJS中的请求和承诺编写网络代码的新手.
我想删除这些嵌套的promises并将它们链接起来,但我不确定我是怎么做的/它是否是正确的方法.
exports.viewFile = function(req, res) {
var fileId = req.params.id;
boxContentRequest('files/' + fileId + '/content', req.user.box.accessToken)
.then(function(response) {
boxViewerRequest('documents', {url: response.request.href}, 'POST')
.then(function(response) {
boxViewerRequest('sessions', {document_id: response.body.id}, 'POST')
.then(function(response) {
console.log(response);
});
});
});
};
Run Code Online (Sandbox Code Playgroud)
这是请求代码:
var baseContentURL = 'https://api.box.com/2.0/';
var baseViewerURL = 'https://view-api.box.com/1/';
function boxContentRequest(url, accessToken) {
return new Promise(function (resolve, reject) {
var options = {
url: baseContentURL + url,
headers: {
Authorization: 'Bearer ' + accessToken,
}
};
request(options, function (err, res) {
if (err) { …Run Code Online (Sandbox Code Playgroud) 在我的Parse Cloude代码中,我需要运行几个连续的查询,每个查询都使用"find()".
例:
var promise = firstQuery.get(objectId).then(function(result1){
return secondQuery.find();
}).then(function(result2){
return thirdQuery.find();
}).then(function(result3) {
// here I want to use "result1", "result2" and "result3"
});
Run Code Online (Sandbox Code Playgroud)
问题是:如何在最后的"then"语句中访问"result1"和"result2",而不将它们分配给父作用域中声明的变量.
为什么我这样问:如果要嵌套一堆你在循环中创建的promises以便它们并行执行,你就不能使用父作用域技巧(想象一下围绕上述语句的for循环,其中所有的promise都是放入一个数组然后使用"Parse.Promise.when"进行评估.它们都会同时开始修改父作用域变量.)
我可以创建某种承诺对象,我可以返回以下内容:
Parse.promise({result:result1,findResult:secondQuery.find()};
Run Code Online (Sandbox Code Playgroud)
所以我可以通过这样做从"result2"参数中获取值
result2.result
Run Code Online (Sandbox Code Playgroud)
和
result2.findResult
Run Code Online (Sandbox Code Playgroud)
我希望我能说清楚.这不是很容易解释.
在Sequelize> = 1.7中,我们可以使用promises
你能解释一下我如何从这个代码中获得每个用户的值:
var User = sequelize.define("user", {
username: Sequelize.STRING
})
User
.sync({ force: true })
.then(function() { return User.create({ username: 'John' }) })
.then(function(john) { return User.create({ username: 'Jane' }) })
.then(function(jane) { return User.create({ username: 'Pete' }) })
.then(function(pete) {
console.log("we just created 3 users :)")
console.log("this is pete:")
console.log(pete.values)
// what i want:
console.log("this is jane:")
console.log(jane.values)
console.log("this is john:")
console.log(john.values)
})
Run Code Online (Sandbox Code Playgroud)
UPD
所有值都需要与其他模型设置关联.其实我需要一些像这样的代码:
User.hasMany(Group)
Group.hasMany(User)
User
.sync({ force: true })
.then(function() { return User.create({ …Run Code Online (Sandbox Code Playgroud) 我在下面有以下承诺链,它看起来很混乱(每个_create*函数返回一个承诺):
return new Promise(function (resolve, reject) {
_this.database.transaction(function (t) {
_this._createExternalAccount(payment, t)
.then(function (externalAccount) {
return _this._createExternalTransaction(externalAccount, payment, t)
.then(function (externalTransaction) {
return _this._createAddress(externalAccount, payment, t)
.then(function (address) {
return _this._createTransaction(address, payment, t)
.then(function (transaction) {
return _this._createGatewayTransaction(externalTransaction, transaction, payment, t)
.then(function (gatewayTransaction) {
t.commit();
resolve(bridgePayment);
});
});
});
});
})
.error(function (bridgePayment) {
t.rollback();
reject(bridgePayment);
});
});
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用Promise函数all(),join()但这些似乎同时运行我无法执行的函数,因为持久化到某些表需要来自先前持久化表的字段.我希望有一些方法让我做以下的事情,但我似乎无法找出如何:
Promise.all(_this._createExternalAccount(payment, t), _this._createExternalTransaction(externalAccount, payment, t), _this._createAddress(externalAccount, payment, t))
.then(function(externalAccount, externalTransaction, address) {
// do logic …Run Code Online (Sandbox Code Playgroud) 我是这样的承诺,
function getMode(){
var deferred = Promise.defer();
checkIf('A')
.then(function(bool){
if(bool){
deferred.resolve('A');
}else{
return checkIf('B');
}
}).then(function(bool){
if(bool){
deferred.resolve('B');
}else{
return checkIf('C');
}
}).then(function(bool){
if(bool){
deferred.resolve('C');
}else{
deferred.reject();
}
});
return deferred.promise;
}
Run Code Online (Sandbox Code Playgroud)
checkIf返回一个promise,是的checkIf ,无法修改.
我如何在第一场比赛中脱颖而出?(除了明确抛出错误之外的任何其他方式?)
所以我有一个帖子集合
{
id: String,
comments: [String], # id of Comments
links: [String], #id of Links
}
Run Code Online (Sandbox Code Playgroud)
评论:{id:String,comment:String,}
链接:{id:String,link:String,}
通过ID查找包含评论和链接的帖子:
Posts.findOne({id: id}, function(post) {
Comments.find({id: post.id}, function(comments) {
Links.find({id: post.id}, function(links) {
res.json({post: post, comments: comment, links: links})
})
})
})
Run Code Online (Sandbox Code Playgroud)
如何使用Promise(http://mongoosejs.com/docs/promises.html)来避免回调地狱?
var query = Posts.findOne({id: id});
var promise = query.exec();
promise.then(function (post) {
var query1 = Comments.find({id: post.id});
var promise1 = query1.exec();
promise1.then(function(comments) {
var query2 = Links.find({id: post.id});
var promise2 = query2.exec();
promise2.then(function(links) {
res.json({post: post, comments: …Run Code Online (Sandbox Code Playgroud) 在闭包标签维基页面中,它显示"jQuery本身就是一个大关闭".
但是也承诺关闭?你能解释一下为什么或为什么不解释?这就是我理解闭包的方法:为变量分配一个函数并在不同的环境中重用它.Promise可以做到这一点$.ajax(),但我无法在stackoverflow中找到将promise作为闭包引入的任何地方.也许是因为有像承诺的其他功能$.Deferred(),resolve()以及fail()扩展其功能,而不仅仅是一个简单的函数传递?
我正在尝试学习一些关于Node和异步编程的知识.我读到了Promises,并试图在一个小项目中使用它们,这个项目将用户的帖子从服务A复制到服务B.我在理解如何最好地在Promises之间传递状态时遇到一些麻烦
该项目是使用Promise库为NodeJS编写的
我当前问题的一个简单定义是:
这是一些伪代码,说明了我如何将Promise链接在一起.
Promise.from('service_A_username')
.then(getServiceAUserIdForUsername)
.then(getServiceAPostsForUserId)
.then(function(serviceAPosts) {
// but what? store globally for access later?
doSomethingWith(serviceAPosts);
return Promise.from('service_B_username');
})
.then(getServiceBUserIdForUsername)
.then(getServiceBPostsForUserId)
.done(function(serviceBPosts) {
// how do we interact with Service A posts?
doSomethingThatInvolvesServiceAPostsWith(serviceBPosts);
});
Run Code Online (Sandbox Code Playgroud)
我想过要做的一些事情:
还有其他选择,建议采用什么方法?
javascript ×10
promise ×10
node.js ×4
bluebird ×2
async-await ×1
asynchronous ×1
chaining ×1
closures ×1
es2017 ×1
mongoose ×1
request ×1
sequelize.js ×1