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对象,也

我读过一些关于承诺的文件,我有一些基本的问题,因为有些时候我读到这是真的,有时不是

我有两个问题需要澄清

  • 如果Java脚本中的每个函数都可以使用promise(通过使用then)调用,或者我应该从函数中返回一些promise对象,也就是说,通过向返回函数添加一些Q来对其进行不同的定义
  • 我看到有一种选择,可以连锁承诺,也可以问所有人,他们之间有什么不同
  • 举个例子会很有帮助

  • 如果Java脚本中的每个函数都可以使用promise(通过使用then)调用,或者我应该从函数中返回一些promise对象,也就是说,通过向返回函数添加一些Q来对其进行不同的定义
  • 承诺使用返回值。如果一个函数不返回一个承诺-将它链接到另一个承诺将不会等待任何事情。链(或聚合,如
    .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.
    });
    
    正确的方法是:

  • 我看到有一种选择,可以连锁承诺,也可以问所有人,他们之间有什么不同
  • Q.all或Promise.all在ES6中是并行的,链接承诺是顺序的:

    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
    });
    
  • 有一些工具或方法来验证承诺是否被链接好吗?因为当我试图错误地忘记某个链函数中的return语句时,它可能会损害进程
  • 是的,Spion不久前为此编写了一个工具,名为
    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
    });