How do I convert an existing callback API to promises? 的可接受答案有这个例子:
function getUserDataAsync(userId){
return new Promise(function(resolve,reject){
getUserData(userId,resolve,reject);
});
}
问题:
Promise
的主体不应该返回一些东西,而不仅仅是调用getUserData
(至少在实际代码中,而不是作为 promise 演示练习)?这个特定的
Promise
也是一个闭包吗?它似乎关闭了userId
,因为getUserDataAsync
使用userId
创建并返回了一个新的Promise
实例,但我想要确定。
最佳答案
Shouldn't the body of Promise return something, not just call
getUserData
(at least in practical code, not as promise demonstration exercise)?
不,它不必。事实上,从 Promise
构造函数返回一个值不会有任何效果。 只有 resolve
和 reject
函数可以实现 Promise
。
Is this particular
Promise
also a closure? It seems like it closes overuserId
, asgetUserDataAsync
creates and returns a newPromise
instance usinguserId
, but I want to be sure.
是的,传递给 Promise
构造函数的函数关闭 userId
。
关于javascript - 澄清 node.js + promises 片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33276715/