Javascript JS承诺/异步澄清问题
我读过一些关于承诺的文件,我有一些基本的问题,因为有些时候我读到这是真的,有时不是 我有两个问题需要澄清Javascript JS承诺/异步澄清问题,javascript,jquery,angularjs,promise,angular-promise,Javascript,Jquery,Angularjs,Promise,Angular Promise,我读过一些关于承诺的文件,我有一些基本的问题,因为有些时候我读到这是真的,有时不是 我有两个问题需要澄清 如果Java脚本中的每个函数都可以使用promise(通过使用then)调用,或者我应该从函数中返回一些promise对象,也就是说,通过向返回函数添加一些Q来对其进行不同的定义 我看到有一种选择,可以连锁承诺,也可以问所有人,他们之间有什么不同 举个例子会很有帮助 如果Java脚本中的每个函数都可以使用promise(通过使用then)调用,或者我应该从函数中返回一些promise对象,也
.all
)知道函数何时完成的方式是使用返回值
function fn1(){
setTimeout(function(){ console.log("Hi"); }, 1000);
}
Promise.resolve.then(function(){ // start empty ES6 promise chain
return fn1();
}).then(function(){
console.log("Bye"); // this will log "Bye Hi" because it did not wait.
});
正确的方法是:
Promise.all([fn1(), fn2(), fn3]).then(function(){
// fn1 fn2 and fn3 complete at an arbitrary order
// code here executes when all three are done
});
fn1().then(fn2).then(fn3).then(function(){
// fn1 executes, when it is done fn2, when it is done fn3,
// then code here
});
thenlint
,您可以找到它。描述说:
用于检查可能的承诺的lint。然后检查使用错误
非常感谢专家!对于这个详细的答案,我投了赞成票!你能提供一个如何使用JS fiddle或其他工具中的thenlint的例子吗,我对这方面的东西很陌生,非常感谢!!!!我很高兴能帮上忙,谢谢你的提问。对于
thenlint
,它被用作命令行工具。您可以使用npm install-g thenlint
安装它,然后通过thenlint yourJSFileWithPromissions.js运行它-您可以在github repo自述文件或。
Promise.all([fn1(), fn2(), fn3]).then(function(){
// fn1 fn2 and fn3 complete at an arbitrary order
// code here executes when all three are done
});
fn1().then(fn2).then(fn3).then(function(){
// fn1 executes, when it is done fn2, when it is done fn3,
// then code here
});