[英]JavaScript Chaining Promises : Calling next promise before previous has finished
Tools: JavaScript ES6 工具:JavaScript ES6
I haven't seen a good succinct answer about the syntax of chaining multiple promises to execute in order. 我还没有看到关于链接多个promises以按顺序执行的语法的简洁答案。 I thought this would be a good nail in the coffin question for all promise newbies out there.
我认为这对于所有承诺新手的棺材问题都是一个很好的指甲。 :)
:)
My Issue is that I want to call this in a synchronous order getPosts--->getThreads--->initializeComplete()
我的问题是我想以同步顺序调用它
getPosts--->getThreads--->initializeComplete()
Here is what I am doing. 这就是我在做的事情。
userPromise.then(getPostsPromise).then(getThreadsPromise).then(initializeComplete());
Here is an example of one of the promises in the chain: 以下是链中一个承诺的示例:
var getPostsPromise = function(){
//Firebase is just a simple server I'm using
var firebasePostsRef = new Firebase("https://myfburl.firebaseio.com/posts");
var postsRef = firebasePostsRef.child(localPlace.key);
return new Promise(function(resolve, reject) {
//Below is a Firebase listener that is called when data is returned
postsRef.once('value', function(snap,prevChild) {
var posts = snap.val();
AnotherFile.receiveAllPosts(posts);
resolve(posts);
});
});
}
But initializeComplete()
is being called before getPostsPromise
and getThreadsPromise
have a chance to finish fetching. 但是在
getPostsPromise
和getThreadsPromise
有机会完成提取之前调用initializeComplete()
。
Why is that happening and how do I write the promises to execute in order? 为什么会发生这种情况?如何编写承诺以按顺序执行?
initializeComplete is getting called right away because you are invoking it when passing it to then
. initializeComplete获取调用的时候了,因为你把它传递给时调用它
then
。 You have to omit the parentheses, just like you did for getPostsPromise
and getThreadsPromise
你必须省略括号,就像你为
getPostsPromise
和getThreadsPromise
所做的那样
userPromise.then(getPostsPromise).then(getThreadsPromise).then(initializeComplete);
While yts's answer is correct (the issue is you're invoking initializeComplete instead of passing the function), I'd rather format the calls a bit differently. 虽然yts的答案是正确的(问题是你正在调用initializeComplete而不是传递函数),我宁愿格式化调用有点不同。 Having each callback function call the next function is a bit against the design of promises.
让每个回调函数调用下一个函数有点违背promises的设计。 I'd rather each function return a promise, and then call
then
on the returned promise: 我宁愿每个函数返回一个承诺,然后调用
then
在返回的承诺:
userPromise
.then(function(){
return getPostsPromise()
}).then(function(){
return getThreadsPromise()
}).then(function(){
return initializeComplete();
});
or to pass the actual returned objects and not have to do any additional intermediate processing: 或者传递实际返回的对象而不必进行任何额外的中间处理:
userPromise
.then(getPostsPromise)
.then(getThreadsPromise)
.then(initializeComplete);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.