Javascript 如何在内部传递JS函数的参数,或者实现类似的行为?
让我们假设有一个promise createPost和一个函数getPosts。第一个在帖子数据库中创建记录并解析。Javascript 如何在内部传递JS函数的参数,或者实现类似的行为?,javascript,asynchronous,promise,Javascript,Asynchronous,Promise,让我们假设有一个promise createPost和一个函数getPosts。第一个在帖子数据库中创建记录并解析。getPosts检索所有帖子,创建UL列表并将其附加到网页 createPost ({*post contents JSON*}) .then(getPosts); 当如上所述调用createPost时,承诺将等待帖子更新,然后运行-getPosts。然而,如果出于某种原因,我想解析并使用一个参数运行getPosts:getPosts(param),它会在promise解析之
getPosts检索所有帖子,创建UL列表并将其附加到网页
createPost ({*post contents JSON*})
.then(getPosts);
当如上所述调用createPost时,承诺将等待帖子更新,然后运行-getPosts。然而,如果出于某种原因,我想解析并使用一个参数运行getPosts:getPosts(param),它会在promise解析之前立即被触发
.then回调函数如何(以及为什么)包含参数而不违背承诺?或者,我如何实现这种行为
编辑:为什么是这样
.then(getPosts(param));
不等待函数解析
.then(() => getPosts(param));
是吗 创建一个满足您需要的函数。大概是这样的:
createPost ({*post contents JSON*})
.then(result => getPosts(param, result));
createPost ({*post contents JSON*})
.then(() => getPosts(param));
此代码将等待createPost
的承诺得到解决,此时它将调用getPosts,传入param
以及createPost
的结果
或者,如果您根本不关心结果,只是createPost已经完成,您可以这样做:
createPost ({*post contents JSON*})
.then(result => getPosts(param, result));
createPost ({*post contents JSON*})
.then(() => getPosts(param));
添加一个包装器内联函数
createPost ({*post contents JSON*})
.then(()=>{getPosts(param1, param2)})
执行此操作时,您正在执行getPosts
方法,并将其返回值作为参数传递给then
方法。如果你这样做的话
createPost ({*post contents JSON*})
.then(function () {
getPosts(param);
});
您正在等待承诺得到解决,并在承诺得到解决后执行getPosts。关于根本问题。假设你有:
function f() {
return 'hello';
}
then()
将函数作为其参数。所以说then(f)
说“在承诺解决后调用f。如果你说then(f())
,你说的是“将调用f的结果(即“hello”)传递给then”。f立即被调用
还要注意,顺便说一句,您传递给then的函数将使用单个参数调用,即then
所附加的承诺的解析。例如:
someAsyncFn() {
/* return a promise that resolves to "foo!!" */
}
someAsyncFn().then(console.log); // this will log foo!!
虽然可能是拙劣的风格,这意味着你可以说
createPost().then(() => param).then(getPosts);
编辑
关于函数何时运行的几句话
// nothing gets invoked when we define a function
function foo() {
return 'bar';
}
let a = foo; // this doesn't invoke foo. a is now a function
let b = foo(); // this *does* invoke foo, b is now 'bar'
let c = () => 'bar'; // the same as defining a function. it doesn't invoke anything
let d = c; // this doesn't invoke c. d is now a function
let e = c(); // this *does* invoke c, e is now 'bar'
当我们说
.then(getPosts) // this doesn't invoke getPosts
.then(getPosts(params)) // this invokes getPosts and passes the result to then
.then(() => getPosts(params))
最后一个公式定义了一个函数(未命名),当调用该函数时(尚未调用),该函数将使用参数调用getPosts。当我们把这个未命名函数传递给then时,我们说,“当承诺得到解决时,调用这个未命名函数,这个未命名函数将调用getPosts”谢谢,这对我帮助很大。你也可以看一下我问题的编辑吗?当然可以。你是说为什么部分吗?我希望我的答案的第一个代码块和一段能够做到这一点。不清楚吗?我相信你已经解释清楚了。但是我仍然不明白为什么()=>{getPosts(param1,param2)}不能像f()那样立即被调用。